简体   繁体   中英

SQL Server SELECT Query using “CASE… END” to select column but getting Column not found error

I have onse SELECT statement to get distinct row and in which I have used "CASE" to get return column data from different table. But, some how in result it's not giving particualar column. Please see below sample query.

SELECT DISTINCT
    T1.Col1,
    T2.Col2,
    CASE WHEN <My Condition > THEN T1.IncomeColumn
    ELSE
     T2.IncomeColumn
    END AS FinalIncome
FROM Table1 as t1  inner join Table2 as T2 on T1.ID = T2.ID

Here, as per above example If I am trying to user results of the query it's throwing "FinalIncome" Column not found error.

I have very lrge and time consuming to get result of this query so, it's difficult to get quick root cause.

please let me know if anyone have idea that what are the possibilties for this issue.

Thanks in advance.

You are missing the WHEN in your CASE statement.

SELECT DISTINCT
    T1.Col1,
    T2.col2,
    CASE 
        WHEN <My Condition> THEN T1.IncomeColumn
        ELSE T2.IncomeColumn
    END AS FinalIncome
FROM Table1 as t1 inner join Table2 as T2 on T1.ID = T2.ID

Can you post the <My Condition> as well?

As Francois correctly points out, you're missing a when in your case . I will add to his answer an alternate form of case :

select distinct
       t1.col1,
       t2.col2,
       case <some expression> when <value> then t1.incomecolumn
       else t2.incomecolumn end as finalincome
  from table1 as t1
       inner join
       table2 as t2 on t1.id = t2.id;

The above is more similar to a switch statement in application, where you create a case for each possible value of an expression that you're interested in.

select distinct
       t1.col1,
       t2.col2,
       case when <my condition> then t1.incomecolumn
       else t2.incomecolumn end as finalincome
  from table1 as t1
       inner join
       table2 as t2 on t1.id = t2.id;

This form is the more verbose of the two, and overkill for some common sitations where you might create a different condition for each value of a pre-defined code ( eg, a status field that only has a few possible values, such as "OPEN", "CLOSED", "PENDING", etc. ).

The advantage this version has is it is the only way of handling null values:

case when <some column> is null then 'null brah' else <some column> end

Attempting to do this with the first syntax will lead to an error:

case <some column> when null then 'null brah' else <some column> end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM