【问题标题】:Search for records that do not contain a specific value搜索不包含特定值的记录
【发布时间】:2021-10-03 14:41:41
【问题描述】:

我有一个包含其他两个表的 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 的地方选择客户 ID,因为它会给我带来所有记录(1 到 4)。我特别需要那些,无论他们拥有哪个 SectionId,都缺少 SectionId=1

谢谢。

【问题讨论】:

  • 根据问题指南,请展示您的尝试并告诉我们您发现了什么(在本网站或其他地方)以及为什么它不能满足您的需求。

标签: sql sql-server tsql group-by not-exists


【解决方案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】:

    试试这个

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

    【讨论】:

    • 这个解决方案也很完美。不幸的是,我无法选择两个答案。谢谢光辉。
    • @Danielle 。 . .我确实注意到这是第一次。
    【解决方案3】:

    查看 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)
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 2023-03-05
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多