Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to return distinct values then filter by date

Tags:

sql

sql-server

How can I select just rows of newly added records, for a specific date, that have not been entered previously?

My source data is:

All data

SELECT DISTINCT 
    Date, IP
FROM
    tblIPs
WHERE
    (Date = '2019-03-25')

This returns:

enter image description here

but 10.0.0.1 does exist previously in the database, so I don't want that to be in my results.

Is there any way I can select unique IP addresses, regardless of the date, and then filter them by the date, 2019-03-25?

like image 861
Mark Tait Avatar asked Apr 24 '26 02:04

Mark Tait


2 Answers

You can use group by and having:

SELECT MIN(Date), IP
FROM tblIPs
GROUP BY IP
HAVING MIN(Date) = '2019-03-25'
like image 101
Gordon Linoff Avatar answered Apr 25 '26 21:04

Gordon Linoff


So you want the IPs that appear on 2019-03-25, and don't appear before that:

SELECT IP FROM tblIPs WHERE DATE = '2019-03-25'
EXCEPT
SELECT IP FROM tblIPs WHERE DATE < '2019-03-25'
;

If you also want to exclude IPs that appear again after 2019-03-25, change the < to <>

like image 36
AakashM Avatar answered Apr 25 '26 20:04

AakashM