4
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

4 回答 4

4

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

select Keyword,COUNT(distinct id) from #Tbl
group by Keyword
having COUNT(distinct id)>1 and MIN(id) = 0
于 2013-06-05T17:11:12.710 回答
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)

这是一个带有演示的sqlfiddle 。

于 2013-06-05T17:11:27.790 回答
2

这应该这样做:

SELECT Keyword
FROM  #Tbl
WHERE Keyword IN (SELECT DISTINCT Keyword FROM #Tbl WHERE ID = 0)
GROUP BY Keyword
HAVING COUNT(DISTINCT id) > 1
于 2013-06-05T17:11:05.563 回答
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)
;
于 2013-06-05T17:32:00.340 回答