【问题标题】:how to join with IIF function?如何加入 IIF 功能?
【发布时间】:2020-01-12 03:37:55
【问题描述】:

您好,我正在使用 MSSQL 2017 并尝试了解此代码的工作原理

DECLARE @customer TABLE (

    credithold bit,
    id int primary key, 
    deliverycityID int,
    postalcityID int
)
DECLARE @city TABLE (

    cityid int primary key, 
    pop bigint
)
INSERT INTO @city VALUES (1,2666),(2,7889),(3,28917)
INSERT INTO @customer VALUES(1,1,2,1),(0,2,3,2),(1,3,1,3),(0,4,2,3)

SELECT c1.id, pop, IIF(credithold = 0, deliverycityID, postalcityID) as cityid
FROM @customer c1
INNER JOIN @city AS A ON A.cityid = cityid 

代码给出的结果如下 (https://i.stack.imgur.com/qxs2G.png) 但我认为它应该像这样返回 (https://i.stack.imgur.com/x3B19.png) https://i.stack.imgur.com/x3B19.png 有什么建议吗?谢谢!

对不起图片,由于声誉不够,我无法直接发布图片。

【问题讨论】:

  • 你想完成什么?
  • 我想了解为什么该查询显示的结果像第一张图片而不是我希望显示的第二张。
  • 您正在将“INNER JOIN @city AS A ON A.cityid = cityid”加入到它自己的列中。唯一具有 cityid 列的表是城市表
  • 我以为第二个 cityid 是 IIF(credithold = 0, deliverycityID, postalcityID) 的别名,不是吗?

标签: sql sql-server tsql join


【解决方案1】:

这样做的正确加入就是这样做:

SELECT c1.id, pop, IIF(credithold = 0, deliverycityID, postalcityID) as cityid
FROM @customer c1
INNER JOIN @city AS A ON A.cityid = IIF(credithold = 0, deliverycityID, postalcityID)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多