簡體   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