繁体   English   中英

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

[英]Find unique column value from records where another column has ALL of the values from a set

假设我有一个这样的表:

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

我想在唯一的ID值中找到具有该ID记录,这些记录在提供的集合中具有所有 Word值。 例如, WHERE Word IN ('a', 'dog', 'has')将返回ID1WHERE Word IN ('a', 'dog', 'has', 'black')将返回NULL

这可能吗?

使用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

如果您使用的是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,','));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM