搜索不包含特定值的记录

Search for records that do not contain a specific value

我有一个 table,其中包含来自另外两个 table 的 ID。那是两个整数。

CustomerId  SectionId
====================
1           1
1           2
1           3
2           2
2           3
3           1
3           2
3           3
4           2
4           3

我要查找的是那些缺少 SectionId=1 的记录。对于上面的示例,我需要检索 CustomerId 2 和 4。

我不能在 SectionId <> 1 处执行 Select 客户 ID,因为它会给我所有记录(1 到 4)。我特别需要那些缺少 SectionId=1

的 SectionId=1

谢谢。

试试这个

select distinct id
from Test
where id not in (
    select distinct id
    from Test
    where section = 1
);

你需要NOT EXISTS:

SELECT DISTINCT t1.CustomerId
FROM tablename t1
WHERE NOT EXISTS (SELECT 1 FROM tablename t2 WHERE t2.CustomerId = t1.CustomerId AND t2.SectionId = 1)

或者,使用条件聚合:

SELECT CustomerId
FROM tablename
GROUP BY CustomerId
HAVING COUNT(CASE WHEN SectionId = 1 THEN 1 END) = 0

检查 2 个例子

Declare @t Table (CustomerId int,  SectionId int)

insert into @t Values
(1, 1),
(1, 2),
(1, 3),
(2, 2),
(2, 3),
(3, 1),
(3, 2),
(3, 3),
(4, 2),
(4, 3)

select DISTINCT CustomerId from @t 
where CustomerId not in (
    select CustomerId from @t
    where SectionId = 1
    group by CustomerId 
)


SELECT DISTINCT t1.CustomerId
FROM @t t1
WHERE NOT EXISTS (SELECT * FROM @t t2 
                  WHERE t2.CustomerId = t1.CustomerId AND t2.SectionId = 1)