【问题标题】:how can i use case statement after using left join?使用左连接后如何使用 case 语句?
【发布时间】:2015-09-18 00:16:10
【问题描述】:
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 语句?

【问题讨论】:

  • 在使用左连接之前你用的是什么?什么不工作?

标签: sql-server case hierarchy


【解决方案1】:

没有什么基本因素可以阻止 CASE 语句与 LEFT (OUTER) JOIN 一起使用,但要记住关于 OUTER 连接的重要一点是外部表中可能存在 NULL 值。

您所写的CASE 声明并未说明这一点,例如(假设 [Descr] 可能为 NULL),在您的声明中:

len([Descr])=0 then [Code] else [Descr] end as [Descr]的情况

如果 [Descr] 为 NULL,len([Descr]) 将评估为 NULL,而不是 0,因此会进入 CASEELSE 子句,无论如何都会返回 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:

按顺序计算参数并返回当前值 第一个最初不计算为 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] 值可能是零长度字符串 (''),并且您想返回其中的另一个字段也可以这样写 Coalesce 语句:

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

NullIf 函数的作用与 Coalesce 正好相反,如果两个表达式相等则返回 NULL,否则返回第一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多