我在这个结构中有我的 table 。我正在尝试查找其单词未出现在列表中的所有唯一 ID。我怎样才能在 MS SQL Server 中实现这一点。
id word
1 hello
2 friends
2 world
3 cat
3 dog
2 country
1 phone
4 eyes
我有一个单词列表
**List**
phone
eyes
hair
body
预期产出
除了列表中的单词,我需要所有唯一的 ID。在这种情况下,
2
3
I & 4 不在输出中,因为它们的词出现在列表中
我试过下面的代码
Select count(distinct ID)
from Table1
where word not in ('phone','eyes','hair','body')
我也试过 Not Exists 也没有用
最佳答案
你也可以试试这个:这是一个动态表结构:
DECLARE @T AS TABLE (id int, word varchar(20))
INSERT INTO @T VALUES
(1, 'hello'),
(2, 'friends'),
(2, 'world'),
(3, 'cat'),
(3, 'dog'),
(2, 'country'),
(1, 'phone'),
(4, 'eyes')
DECLARE @tblNotUsed AS TABLE ( id int, word varchar(20))
DECLARE @tblNotUsedIds AS TABLE (id int)
INSERT INTO @tblNotUsed VALUES
(1, 'phone'),
(2, 'eyes'),
(3, 'hair'),
(4, 'body')
INSERT INTO @tblNotUsedIds (id)
SELECT [@T].id FROM @T INNER JOIN @tblNotUsed ON [@tblNotUsed].word = [@T].word
SELECT DISTINCT id FROM @T
WHERE id NOT IN (SELECT id FROM @tblNotUsedIds)
关于sql - 替代 SSMS 中的 NOT IN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55146520/