从记录中查找唯一的列值,其中另一列具有集合中的所有值

时间:2018-10-11 20:38:54

标签: sql sql-server tsql

假设我有一个这样的表:

+----+-------+
| ID | Word  |
+----+-------+
|  1 | a     |
|  1 | dog   |
|  1 | has   |
|  2 | two   |
|  2 | three |
|  2 | four  |
|  2 | five  |
|  3 | black |
|  3 | red   |
+----+-------+

我想找到唯一的ID值,其中包含具有ID值的Word所有 all 的记录。例如。 WHERE Word IN ('a', 'dog', 'has')将返回ID1,但WHERE Word IN ('a', 'dog', 'has', 'black')将返回NULL

这可能吗?

2 个答案:

答案 0 :(得分:3)

使用group byhaving

select id
from t
where word in ('a', 'dog', 'has')
group by id
having count(*) = 3;  - the number of words in the list

答案 1 :(得分:0)

如果您使用的是SQL 2016或更高版本,这似乎是一个不错的解决方案:

--Load test data
DECLARE @tbl as TABLE (id int, word varchar(40))
INSERT INTO @tbl
(id, word)
VALUES
(1, 'a'),(1,'dog'),(1,'cat'),(1,'has'),(1,'a'),(2,'two'),(2,'three'),(2,'four'),(2,'five'),(3,'black'),(3,'red')

--ACTUAL SOLUTION STARTS HERE
DECLARE @srch as VARCHAR(200)
SET @srch = 'a,dog,has'

SELECT id 
FROM @tbl
WHERE word IN (SELECT value FROM STRING_SPLIT(@srch,','))
GROUP BY id
HAVING COUNT(DISTINCT word) = (SELECT COUNT(DISTINCT value) FROM STRING_SPLIT(@srch,','));