我有以下数据:
ID Site
2 NULL
2 32
3 6
4 7
8 12
8 13
9 14
9 14
结果应该是:
ID Site
2 NULL
2 32
8 12
8 13
请注意,结果发现ID和Site的唯一组合,对于给定的ID重复不止一次。
我执行了以下查询,但没有返回结果:
select distinct id, site
from Table1
group by id, site
having count(*) > 1
order by id
SELECT
ID,
site
FROM table1
WHERE ID IN (
SELECT ID
FROM (
SELECT ID ,site
FROM table1
GROUP BY ID ,site
) x
GROUP BY ID
HAVING count(*)>1
)
看到:DBFIDDLE
SELECT ID, site FROM table1 GROUP BY ID, site
将选择不同的值。- 然后,使用
HAVING count(*) > 1
,只过滤出现不止一次的id。
注:您应该尽量避免在一个查询中使用DISTINCT
和GROUP BY
。当你这样做的时候,生活会变得更加复杂……😉
一种方法是在CTE中执行select distinct
,然后使用count
窗口函数来获得所需的结果:
with u as (
select distinct *
from Table1
), v as (
select *
, count(*) over(partition by ID) as cnt
from u
)
select ID, Site
from v
where cnt > 1;
小提琴