使用 Case 语句时排除列的 return NULL 行

Exclude rows that return NULL for a column when using a Case statement

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

这个查询 return 对我来说有 10 行,但是 1 行显示列 objecturl 为 NULL,如果在 [locations] table 中没有找到记录,就会发生这种情况。 =14=]

如何更改我的查询以确保当 objecturl 为 NULL 时,该行未被 return 编辑,因此在我的情况下我的查询只会 return 9 行.

将其添加到 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

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