案例陈述基于3个表MSSQL

时间:2017-10-03 15:05:11

标签: sql-server sql-server-2008

我需要根据3个表编写一个case语句,这样如果表A中的第1列为空,则从表B中查找第2列,如果第2列为空,则从表C中查找第3列

TableA
Column 1a   Column 1
 1           

TableB
Column 1a   Column 2
 1           

TableC
Column 1a  Column 3
     1           A

如果我有表A和B,即两个表,我会写一些类似的东西: -

Case when Column A = '' or Column A is null then Column B
else Column A
from tableA a 
Left join TableB b on a.column 1a = b.column 1a

但我不确定如何在case语句中包含3列。感谢帮助!

2 个答案:

答案 0 :(得分:3)

您可以将coalesce()nullif()一起使用,如下所示:

select 
    a.Column1a
  , Value = coalesce(nullif(a.Column1,''),nullif(b.Column2,''),c.Column3)
from TableA a
  left join TableB b
    on a.Column1a = b.Column1a
  left join TableC c
    on a.Column1a = c.Column1a

coalesce()将返回参数中的第一个非null值,nullif(...,'')将返回null而不是空字符串''

相当于:

select 
    a.Column1a
  , Value = case when a.Column1 is not null and a.Column1 <> '' then a.Column1
                 when b.Column2 is not null and b.Column2 <> '' then b.Column2
                 else c.Column3
                 end
from TableA a
  left join TableB b
    on a.Column1a = b.Column1a
  left join TableC c
    on a.Column1a = c.Column1a

答案 1 :(得分:2)

您可以像这样嵌套CASE语句:

CASE
    WHEN ColumnA = '' OR ColumnA IS NULL
       THEN
           CASE
               WHEN ColumnB = '' OR ColumnB IS NULL
                  THEN ColumnC
               ELSE ColumnB
           END
   ELSE ColumnA
END