Alias Column name in mutiple case statement

2019-01-29 12:23发布

问题:

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


标签: sql oracle case