Alias Column name in mutiple case statement

久未见 提交于 2019-12-29 09:58:18

问题


I am trying to retrieve a value for a alias column using case statement.

CASE 
    WHEN FieldA = 'TestA' THEN FieldA1
    WHEN FieldB = 'TestB' THEN FieldB1
    ELSE NULL
END AS Alias1 

But when I try to use this alias to retrievce value for another alias , I am getting an error

CASE
    WHEN Alias1 = FieldA1 THEN FieldA0
    WHEN Alias1 = FieldB1 THEN FieldA1
    ELSE NULL
END AS Alias2 

Error message I get is :

Can you suggest a way to get rid of the error or any alternative approach which fulfills my requirements


回答1:


You can't use column aliases in the same SELECT clause. You have two choices:

Use a subquery:

SELECT Alias1,
       CASE
            WHEN Alias1 = FieldA1 THEN FieldA0
            WHEN Alias1 = FieldB1 THEN FieldA1
            ELSE NULL
       END AS Alias2 
FROM (
    SELECT CASE 
                WHEN FieldA = 'TestA' THEN FieldA1
                WHEN FieldB = 'TestB' THEN FieldB1
                ELSE NULL
           END AS Alias1,
           FieldA1
           FieldB1
    ...)

or you can repeat the logic that you used in the first CASE:

SELECT CASE 
            WHEN FieldA = 'TestA' THEN FieldA1
            WHEN FieldB = 'TestB' THEN FieldB1
            ELSE NULL
       END AS Alias1,
       CASE 
            WHEN FieldA = 'TestA' THEN FieldA0
            WHEN FieldB = 'TestB' THEN FieldB0
            ELSE NULL
       END AS Alias2


来源:https://stackoverflow.com/questions/23001886/alias-column-name-in-mutiple-case-statement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!