编写一个SQL查询,该查询检索列中具有相同值的所有不同行,其中这些行的计数大于1

时间:2010-11-20 01:42:46

标签: sql count distinct

基本上我需要找到名称超过1的所有ID

所以输出应该是

 (2,a)(2,b)(4,a)(4,b)(4,c) 


id名称
1 a
2 a
2 b
3 c
3 c
4 a
4 b
4 c

我的查询工作

select * from (select distinct * from test) t group by t.id having count(*) > 1

但我认为可能有一个更简单的解决方案,所以是的,有一个简单的解决方案,如果是的话,它是什么?提前谢谢。

2 个答案:

答案 0 :(得分:4)

Select
  Id,
  Name
FROM test 
Group By Id, Name
Having Count(Distinct(Name)) > 1

答案 1 :(得分:1)

您可以尝试以下几种方法:

select id, name
from T
where exists (
  select * from T as Tcopy
  where Tcopy.id = T.id
  and Tcopy.name <> T.name
);

with IDmultipleNames(id) as (
  select id
  from T
  group by id
  having min(name) <> max(name)
)
  select id, name
  from T
  where T.id in (
    select id from IDmultipleNames
  )