获取具有多个值的记录,并且其中至少有一个值为零

时间:2013-06-05 17:07:35

标签: sql sql-server tsql

Create table #Tbl
(
ID int not null,
Keyword nvarchar(max)
)
Insert into #Tbl Values ('0','Cryptography')
Insert into #Tbl Values ('1','Cryptography')
Insert into #Tbl Values ('4','Cryptography')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('0','SQL')
Insert into #Tbl Values ('3','Cloud Computing')
Insert into #Tbl Values ('6','Recursion')
Insert into #Tbl Values ('8','Recursion')
Insert into #Tbl Values ('0','Universe')
Insert into #Tbl Values ('0','Universe')
Insert into #Tbl Values ('7','Universe')

我需要获得具有多个ID的标题,并且至少有一个ID为零。

所以预期结果将是:

Cryptography
Universe

我尝试过以下查询,但无法添加“至少一个id为零”条件

select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1

我该怎么办?谢谢你的帮助。

4 个答案:

答案 0 :(得分:4)

假设您的ID从0开始,以下内容应该可以正常工作

select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1 and MIN(id) = 0

答案 1 :(得分:3)

有很多方法可以做到这一点,例如:

SELECT DISTINCT Keyword
FROM #Tbl T
WHERE EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
              AND ID = 0)
AND EXISTS (SELECT 1 FROM #Tbl WHERE Keyword = T.Keyword
              AND ID != 0)
带有演示的

Here is a sqlfiddle

答案 2 :(得分:2)

这应该这样做:

SELECT Keyword
FROM  #Tbl
WHERE Keyword IN (SELECT DISTINCT Keyword FROM #Tbl WHERE ID = 0)
GROUP BY Keyword
HAVING COUNT(DISTINCT id) > 1

答案 3 :(得分:1)

这是另一种方法:

SELECT Keyword, COUNT(DISTINCT ID)
FROM #Tbl
GROUP BY Keyword
HAVING COUNT(DISTINCT ID) > ALL (SELECT COUNT(DISTINCT NULLIF(ID, 0)) UNION ALL SELECT 1)
;