假设我有一个这样的表:
+----+-------+
| 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')
将返回ID
值1
,但WHERE Word IN ('a', 'dog', 'has', 'black')
将返回NULL
。
这可能吗?
答案 0 :(得分:3)
使用group by
和having
:
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,','));