【问题标题】:Query to find null of specific column with multiple entries查询以查找具有多个条目的特定列的空值
【发布时间】:2021-06-04 12:40:04
【问题描述】:

使用下面的示例,我想查找列中具有空值的所有用户,即使他们在该表中有多个条目。所以例如我有一个这样的表:

ID userid col1 col2 col3
1 user1 a null b
2 user1 b a b
3 user2 a null b
4 user2 b null b

我只想返回 user2,因为它的 col2 没有为任何行填充任何内容。但是,如何创建一个不会让我返回 user1 的查询,因为 user1 在其中一行中确实有 col2 的值。 User1 不断被拉取,因为它确实有一行 col2 为空。基本上任何 userId 在此表的任何行中的 col2 中都没有填充任何内容。如果 userId 在 col2 中确实有值,则不要返回该 userId。

我尝试过这样的事情:

select distinct(a.userid) from User a
group by a.userid 
having a.col is null

【问题讨论】:

  • 您是否希望返回两个用户行?尝试使用NOT EXISTS,如果不起作用,请将您尝试过的查询添加到您的问题中。

标签: sql sql-server tsql null exists


【解决方案1】:

使用NOT EXISTS:

SELECT DISTINCT u1.userid
FROM User u1
WHERE NOT EXISTS (SELECT 1 FROM User u2 WHERE u2.userid = u1.userid AND u2.col2 IS NOT NULL)

【讨论】:

    【解决方案2】:

    如果你只想要用户,你可以使用聚合:

    select user
    from t
    group by user
    having max(col1) is null or
           max(col2) is null or
           max(col3) is null;
    

    MAX()(或大多数聚合函数)仅当所有值都是 NULL 时才返回 NULL。你也可以使用COUNT()

    having count(col1) = 0 or
           count(col2) = 0 or
           count(col3) = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-12
      • 2017-09-27
      • 1970-01-01
      • 2016-05-21
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2021-07-26
      相关资源
      最近更新 更多