2017-04-06 61 views
1

这里是我的数据看起来像查找重复的日期由某个ID在一个表中

ID   Date    Other Field 
123  1/2/2017  a 
123  1/3/2017  b 
123  1/3/2017  c 
123  1/5/2017  d 
123  1/6/2017  e 
123  1/6/2017  f 
456  2/4/2017  g 
456  2/4/2017  h 
456  2/5/2017  i 
456  2/6/2017  j 

我期待,以确定当存在由ID重复的日期,我想返回整个记录。结果看起来像

ID  Date   Other Field 
123  1/3/2017  b 
123  1/3/2017  c 
123  1/6/2017  e 
123  1/6/2017  f 
456  2/4/2017  g 
456  2/4/2017  h 

我不知道如何识别单个表内的重复日期,然后单独返回这些记录。

任何帮助,非常感谢!

回答

1
select 
t1.* from 
table t1 
join 
(select id,date,count(*) from 
table t2 
group by id,date 
having count(*)>=2 
) t2 
on t1.id=t2.id and t1.date=t2.date 
+0

如果有在子查询指出2以上的HAVING语句? – baineschile

+0

@baineschile:是的,我错过了,现在加入 – TheGameiswar

+0

感谢您的帮助!弄清楚了。 – baineschile

0

您使用的数据库是?如果它支持的窗口函数(例如,Oracle或PostgreSQL的),则:

select 
    id, "date", other_field 
from 
(
    select 
    tbl.*, 
    count(*) over (partition by id, "date") date_cnt 
    from tbl 
) 
where date_cnt >= 2 
+0

ssms 16,但我想出了解决方案。感谢您的答复。 – baineschile

+0

@baineschile你可以发布解决方案吗? – avd

+0

我使用了顶级解决方案。它需要一个HAVING子句来工作。 – baineschile

相关问题