SQL返回多个变量

时间:2017-02-22 23:18:55

标签: sql case

我正在尝试用case语句编写查询。我在将case语句输出为多个变量时遇到问题。基本上我想取1列,然后把第一部分作为outputcolumn1“FIRST”,最后4个字符作为outputcolumn2“LAST”

我尝试过做一些研究,但我找不到任何可以解决我的问题... 我知道我忽略了一些非常愚蠢的东西。

Select *
Case When a.col_1 is NULL 
-- Grab all but last 4 as "FIRST"
Then LEFT(b.col_1, len(b.col_1) -4
-- Grab Last 4 as "LAST"
AND RIGHT(b.col_1, 4)
Else LEFT(a.col_1, len(a.col_1) -4
AND RIGHT(a.col_1, 4)

end as FIRST,LAST

From Table_1 as a
inner join Table_2 as b on a.TableID = b.TableID

1 个答案:

答案 0 :(得分:5)

首先,这里缺少右括号:LEFT(b.col_1, len(b.col_1) -4

其次,你不能返回两列,使用两个case语句。

SELECT *,
       CASE WHEN a.col_1 IS NULL 
            THEN LEFT(b.col_1, LEN(b.col_1) -4) 
            ELSE LEFT(a.col_1, LEN(a.col_1) -4)
       END AS FIRST,
       CASE WHEN a.col_1 IS NULL 
            THEN RIGHT(b.col_1, 4) 
            ELSE RIGHT(a.col_1, 4)
       END AS LAST
FROM Table_1 AS a
INNER JOIN Table_2 AS b 
ON a.TableID = b.TableID

我建议您使用另一种语法:

SELECT *,
       COALESCE(LEFT(a.col_1, LEN(a.col_1) - 4), LEFT(b.col_1, LEN(b.col_1) - 4)) AS FIRST,
       COALESCE(RIGHT(b.col_1, 4), RIGHT(a.col_1, 4)) AS LAST
FROM Table_1 AS a
INNER JOIN Table_2 AS b 
ON a.TableID = b.TableID