如何在SQL Server中查找具有重复值的列

时间:2016-06-17 16:17:14

标签: sql-server-2008

我有一张桌子:

create table #t
(     
    ID int,      
    value nvarchar(5)
)

insert #t 
values (1,'A'), (2, 'B'), (3, 'A'), (3, 'B')

示例数据:

ID  value    
------------
1   A    
2   B    
3   A    
3   B

对于我的项目,我需要具有两个值

的ID

结果:

ID
3

请帮助我。

1 个答案:

答案 0 :(得分:0)

获取具有2个值的ID

select id 
from #t
group by id
having count(distinct value) >= 2

或获取所有具有A和B的ID

select id 
from #t
where value in ('A','B')
group by id
having count(distinct value) = 2

或使其更通用以获取具有所有值的ID

select id 
from #t
group by id
having count(distinct value) = (select count(distinct value) from #t)