【问题标题】:Exclude rows that return NULL for a column when using a Case statement使用 Case 语句时排除对列返回 NULL 的行
【发布时间】:2015-04-02 16:31:14
【问题描述】:
SELECT ir.objectid,ir.objecttype,ir.name,ir.email,ir.createdate,
CASE objecttype
    WHEN 1 THEN (select friendlyurl
        from locations
        where id = ir.objectid)
END as objecturl
FROM inforequests ir
WHERE createdate > '1/1/2014' 
order by CreateDate asc

此查询为我返回 10 行,但有 1 行显示列 objecturl 为 NULL,如果在 [locations] 表中找不到记录,则会发生这种情况。

如何更改我的查询以确保当 objecturl 为 NULL 时,不返回该行,所以在我的情况下,我的查询将只返回 9 行。

【问题讨论】:

    标签: tsql null case


    【解决方案1】:

    将其添加到WHERE 子句中:

    where createdate > '1/1/2014' and objecttype = 1
    

    由于您的CASE 不处理任何其他值,所以当objecttype <> 1 时将导致NULL。

    或者,您可以嵌套SELECTs:

    select *
      from ( SELECT ir.objectid,ir.objecttype,ir.name,ir.email,ir.createdate,
      CASE objecttype
          WHEN 1 THEN (select friendlyurl
              from locations
              where id = ir.objectid)
      END as objecturl
      FROM inforequests ir
      WHERE createdate > '1/1/2014' ) as Temp
    where objecturl is not NULL
    order by CreateDate asc
    

    请注意,这有些不同,因为它还会排除相关子查询返回 NULL 的行。

    【讨论】:

    • 你的第一个建议对我不起作用,嵌套解决方案对我有用。谢谢!
    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多