【问题标题】:TSQL - using case switch to select variable from different left joinsTSQL - 使用案例切换从不同的左连接中选择变量
【发布时间】:2017-06-26 16:32:01
【问题描述】:

我正在尝试将 2 个表连接在一起。问题是有几种方法可以做到这一点,从最佳连接逻辑到更差的连接逻辑。我多次使用同一张表的左连接,每次使用不同的连接条件,然后我想使用case 开关从最佳匹配中选择变量值。更好地解释它的例子如下:

select s.Product, 
    (case when c1.ID is not null then c1.ID
    case when c2.ID is not null then c2.ID
    case when c3.ID is not null then c3.ID
    case when c4.ID is not null then c4.ID
    else NULL) as ID
from
    dbo.Table1 as s 
    left join [dbo].Table2 as c1 on %some join logic%
    left join [dbo].Table2 as c2 on %some join logic%
    left join [dbo].Table2 as c3 on %some join logic%
    left join [dbo].Table2 as c4 on %some join logic%
where
    (
        c1.SKU is not null
        or c2.sku is not null
        or c3.sku is not null
        or c4.sku is not null
    )

问题是这些东西不起作用 - 我只是收到一个错误'Incorrect syntax near the keyword 'case'。'在第 3 行(第二个 case 开关)。有什么建议可以解决这个问题吗?

【问题讨论】:

  • 您在CASE 中缺少ENDCASE ... END
  • @Eric 不,我已经试过了——同样的错误信息

标签: sql sql-server tsql left-join case


【解决方案1】:

您甚至不需要CASE 表达式来处理您的选择逻辑。相反,您可以使用COALESCE() 函数按照您想要的顺序选择第一个不是NULL 的ID:

select
    s.Product,
    coalesce(c1.ID, c2.ID, c3.ID, c4.ID) AS ID
from dbo.Table1 as s
...

如果您想使用原来的 CASE 表达式,那么我们可以通过不对每个条件重复 CASE 关键字来纠正它:

select
    s.Product,
    case when c1.ID is not null then c1.ID
         when c2.ID is not null then c2.ID
         when c3.ID is not null then c3.ID
         when c4.ID is not null then c4.ID end as ID
from dbo.Table1 as s
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2015-06-19
    • 2016-11-13
    • 2013-01-15
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多