SQL Server – Finding Rows with Same ID but Different Date

sql serversql-server-2012

Consider below table tbl:

id    date
1     2016
1     2017
2     2017
2     2017
3     2016
3     2017
4     2018
5     2018

How can I get only rows with same id but different date.

Right now I can only get ids with more than 1 count like so:

select id, date
from tbl
group by id
having count(id)>1

How can I only get id 1 and 3 along with date?

Best Answer

Use an AGGREGATE function like MIN or MAX.

If you only want one record per ID, you have to choose which date you want. The first (MIN) or the latest (MAX).

https://docs.microsoft.com/en-us/sql/t-sql/functions/aggregate-functions-transact-sql?view=sql-server-2017

^^Above information is not what was requested.

Edited per clarification in comments: Just use the HAVING to identify which ID values have more than one date, then apply that to a new SELECT.

SELECT id, Date
FROM tbl
WHERE id IN
    (
        select id 
        from tbl
        group by id
        having count(distinct date)>1
    )