【问题标题】:SQL select distinct exclude NULL rows [closed]SQL选择不同的排除NULL行[关闭]
【发布时间】:2020-08-28 15:44:59
【问题描述】:

SQL 查询:

SELECT DISTINCT [File Version Number], [Enrollment Employee ID] 
FROM Participant

结果:

+---------------------+------------------------+
| Fule Version Number | Enrollment Employee ID |
+---------------------+------------------------+
| null                | null                   |
| null                | 1100527                |
| null                | 5032506                |
| v2.2.0              | null                   |
+---------------------+------------------------+

期望的结果:排除具有 NULL 数据的行;第一行。

我知道我们可以在两列上使用 where 子句来过滤空行,但是如果我们有大量的列要选择,并且我们不想有很长的 where 子句怎么办?

任何解决方案或解决方法都将受到高度赞赏。谢谢。

【问题讨论】:

  • 如果你可以coalesce各个列,即有一些兼容的数据类型,结果is null那么它们都是null
  • 你能用dynamic sql吗?检查这是否可以帮助你stackoverflow.com/questions/780337/…
  • WHERE 正是您想要的。
  • 你使用什么 SGBDR?
  • 如果只有第一行,“WHERE [Enrollment Employee ID] IS NOT NULL OR [File Version Number] IS NOT NULL”?

标签: sql sql-server where-clause sql-null


【解决方案1】:

如果要排除所有值为NULL 的行,则需要WHERE 子句:

Select Distinct [File Version Number], [Enrollment Employee ID] 
From Participant
where [File Version Number] is not null or [Enrollment Employee ID] is not null;

如果您关心的是编写查询,那么您可以通过使用数据库的元数据表来促进这一点。您可以使用 SQL 或电子表格或其他工具查询“列”元数据以构造 where 子句。

【讨论】:

    【解决方案2】:

    如果您打算在纯 SQL(没有动态 SQL)中执行此操作,那么,您将需要以一种或另一种方式枚举列名。

    基本解决方案是使用or条件:

    where col1 is not null or col2 is not null ... or coln is not null;
    

    您也可以使用coalesce() - 正如 HABO 所评论的那样:

    where coalesce(col, col2, ..., coln) is not null
    

    concat_ws() 也浮现在脑海中——这与coalesce() 的逻辑真的是一样的:

    where concat_ws(col1, col2, ..., coln) is not null
    

    最后,我们还可以使用cross apply 进行反透视,然后聚合:

    select ...
    from participant p
    cross apply (
        select count(col) cnt
        from (values (p.col1), (p.col2), ..., (p.coln)) x(col)
    ) x
    where cnt > 0
    

    【讨论】:

      【解决方案3】:

      您可以尝试使用 INNER JOIN,例如:

      SELECT DISTINCT [File Version Number], [Enrollment Employee ID] 
      FROM Participant AS p1
      INNER JOIN Participant AS p2 ON p1.[Enrollment Employee ID] = p2.[Enrollment Employee ID]
      WHERE FileVersionNumber IS NOT NULL AND EnrollmentEmployeeID IS NOT NULL;
      
      

      但在这种情况下,您必须加入任何可能包含 NULL 值的每个字段。

      所以我建议你还是应该添加一个where语句:

      SELECT DISTINCT [File Version Number], [Enrollment Employee ID] 
      FROM Participant
      WHERE FileVersionNumber IS NOT NULL AND EnrollmentEmployeeID IS NOT NULL;
      

      【讨论】:

      • inner join 不是outer join,将排除join 条件为空的行,因此无需添加where 子句,只要每列都是加入了自己。单个inner join 就足够了,因为所有列都可以集中到一个on 子句中。除了不清楚之外,这对where 子句有何改进尚不清楚。
      猜你喜欢
      • 2013-10-30
      • 2020-09-04
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多