A few more ways to get the same result:
First, using min(date) < max(date)
as the HAVING
condition - instead of the count(distinct date) > 1
. Perhaps slightly more efficient:
select id, date
from tbl
where id in
( select id
from tbl
group by id
having min(date) < max(date)
) ;
or with a JOIN
:
select t.id, t.date
from tbl as t
join
( select id
from tbl
group by id
having min(date) < max(date)
) as g
on g.id = t.id ;
and one converting the IN
to a correlated EXISTS
subquery. Bonus, we can remove the GROUP BY
:
select id, date
from tbl as t
where exists
( select 1
from tbl as t2
where t.id = t2.id
and t.date <> t2.date
) ;
Another that uses window functions:
select id, date
from
( select id, date,
diff_dates = case when min(date) over (partition by id)
< max(date) over (partition by id)
then 1
end
from tbl
) as d
where diff_dates = 1 ;
and last, one for the obfuscation contest:
select id, date from tbl
except
select id, min(date) from tbl group by id
intersect
select id, max(date) from tbl group by id ;
Test in dbfiffle.
UNIQUE
constraint defined and it's not just what you show here ;)