如何执行此选择?

时间:2010-12-24 09:48:57

标签: sql sql-server tsql

说我有下面的简单表格:

KeyWordID   KeyWord
----------- ----------
1           Blue
3           Yellow
1           Yellow

如何选择KeyWordID,选择KeyWord为蓝色黄色的KeyWordID。

E.g。它应该只返回1,因为这是唯一具有两者关键字蓝色和黄色的KeyWordID

我最初认为GROUPBY - 但它并没有按预期工作。

4 个答案:

答案 0 :(得分:4)

查询

DECLARE @TABLE TABLE (KeyWordID INT, KeyWord VARCHAR(20))

INSERT INTO @TABLE VALUES (1, 'Blue')
INSERT INTO @TABLE VALUES (3, 'Yellow')
INSERT INTO @TABLE VALUES (1, 'Yellow')

SELECT KeyWordID FROM @TABLE
WHERE KeyWord IN ('Blue', 'Yellow') -- Keywords to find
GROUP BY KeyWordID HAVING COUNT(*) = 2 -- Number of keyword to find

结果

KeyWordID
-----------
1

在jzd发表评论后编辑忽略可能的误报:

DECLARE @TABLE TABLE (KeyWordID INT, KeyWord VARCHAR(20))

INSERT INTO @TABLE VALUES (1, 'Blue')
INSERT INTO @TABLE VALUES (1, 'Yellow')
INSERT INTO @TABLE VALUES (3, 'Yellow')
INSERT INTO @TABLE VALUES (3, 'Yellow')

SELECT KeyWordID FROM @TABLE
WHERE KeyWord IN ('Blue', 'Yellow') -- Keywords to find
GROUP BY KeyWordID HAVING COUNT(DISTINCT KeyWord) = 2 -- Number of keyword to find

答案 1 :(得分:3)

加入表格本身应该做的诀窍:

SELECT a.KeywordId
FROM MyTable AS a
INNER JOIN MyTable AS b ON a.KeywordId = b.KeywordId
WHERE a.KeyWord = 'Blue'
AND b.KeyWord = 'Yellow'

答案 2 :(得分:2)

SELECT KeyWordID FROM <YOUR_TABLE> WHERE KeyWord= 'Blue'
INTERSECT
SELECT KeyWordID FROM <YOUR_TABLE> WHERE KeyWord= 'Yellow'

答案 3 :(得分:1)

SELECT KeywordID, COUNT(*) AS BlueAndYellow
FROM myTable
WHERE (Keyword = 'Blue' OR Keyword = 'Yellow')
GROUP BY KeywordID
HAVING COUNT(*) = 2

注意:我没试过这个。但我想这应该有用,并给你一个方法。