使用左连接后如何使用 case 语句?

how can i use case statement after using left join?

select t1.Name, t1.[Code], t2.Name as ParentName
      ,case when len(t2.[ParentCode]) = '' then t1.[Code] else t2.[ParentCode] end as t1.[ParentCode]
      ,case when len([Descr])=0 then [Code] else [Descr] end as [Descr]
      ,t1.[Cumulative]
      ,t1.[Expense]
      ,t1.[Accts]
      ,t1.[Admin]
      ,t1.[Assessment]
      ,t1.[Balance]
      ,t1.[Fiber]
      ,t1.[GL]
      ,t1.[LV]
      ,t1.[Slush]
from [KR].[pl].[Accounts] as t1
left join [KR].[pl].[Accounts] t2 on t1.ParentCode = t2.ParentCode

我正在尝试使用 case 语句来填充空白列,在我使用左连接之前,它工作正常,但在我使用左连接之后它不再工作了。有没有办法用左连接来处理那些 case 语句?

没有什么基本的东西可以阻止 CASE 语句与 LEFT (OUTER) JOIN 一起使用,但是关于 OUTER 联接要记住的重要一点是外部 table 中可能有 NULL 值.

您的 CASE 陈述没有说明这一点,例如(假设 [Descr] 可以为 NULL),在您的语句中:

case when len([Descr])=0 then [Code] else [Descr] end as [Descr]

如果 [Descr] 为 NULL,

len([Descr]) 将计算为 NULL,而不是零,因此落入 CASE、return 的 ELSE 子句无论如何都要输入 NULL 字段。

使用 CASE 的正确写法是:

CASE WHEN len(IsNull([Descr], '')) = 0 THEN [Code] ELSE [Descr] END AS [Descr]

但是有一个更简单的方法,使用 Coalesce 函数:

Coalesce([Descr], [Code]) AS [Descr]

MSDN on Coalesce says:

Evaluates the arguments in order and returns the current value of the first expression that initially does not evaluate to NULL.

因此您的查询变为:

select t1.Name, t1.[Code], t2.Name as ParentName
      ,Coalesce(t2.[ParentCode], t1.[Code]) AS [ParentCode]
      ,Coalesce([Descr], [Code]) AS [Descr]         
      ,t1.[Cumulative]
      ,t1.[Expense]
      ,t1.[Accts]
      ,t1.[Admin]
      ,t1.[Assessment]
      ,t1.[Balance]
      ,t1.[Fiber]
      ,t1.[GL]
      ,t1.[LV]
      ,t1.[Slush]
from [KR].[pl].[Accounts] as t1
left join [KR].[pl].[Accounts] t2 on t1.ParentCode = t2.ParentCode

编辑: 要添加的一件事 - 如果 [ParentCode] 或 [Descr] 的值可能是零长度字符串 (''),并且您想 return 在那种情况下也是另一个字段,然后像这样编写 Coalesce 语句:

Coalesce(NullIf(t2.[ParentCode], ''), t1.[Code]) AS [ParentCode]
Coalesce(NullIf([Descr], ''), [Code]) AS [Descr]  

NullIf 函数与 Coalesce 相反,return如果两个表达式相等则为 NULL,否则为第一个。