SQL: Alias Column Name for Use in CASE Statement

前端 未结 11 1773
悲哀的现实
悲哀的现实 2020-12-04 21:38

Is it possible to alias a column name and then use that in a CASE statement? For example,

SELECT col1 as a, CASE WHEN a = \'test\' THEN \'yes\' END as value          


        
相关标签:
11条回答
  • 2020-12-04 22:00

    It should work. Try this

    Select * from
                  (select col1, col2, case when 1=1 then 'ok' end as alias_col
                   from table)
            as tmp_table
    order by 
           case when @sortBy  = 1 then tmp_table.alias_col end asc
    
    0 讨论(0)
  • 2020-12-04 22:01

    This:

    SELECT col1 as a,
           CASE WHEN a = 'test' THEN 'yes' END as value 
      FROM table;
    

    ...will not work. This will:

    SELECT CASE WHEN a = 'test' THEN 'yes' END as value
      FROM (SELECT col1 AS a
              FROM TABLE)
    

    Why you wouldn't use:

    SELECT t.col1 as a,
           CASE WHEN t.col1 = 'test' THEN 'yes' END as value 
      FROM TABLE t;
    

    ...I don't know.

    0 讨论(0)
  • 2020-12-04 22:01

    Not in MySQL. I tried it and I get the following error:

    ERROR 1054 (42S22): Unknown column 'a' in 'field list'
    0 讨论(0)
  • 2020-12-04 22:02

    In MySql, alice name may not work, therefore put the original column name in the CASE statement

     SELECT col1 as a, CASE WHEN col1 = 'test' THEN 'yes' END as value FROM table;
    

    Sometimes above query also may return error, I don`t know why (I faced this problem in my two different development machine). Therefore put the CASE statement into the "(...)" as below:

    SELECT col1 as a, (CASE WHEN col1 = 'test' THEN 'yes' END) as value FROM table;
    
    0 讨论(0)
  • 2020-12-04 22:04

    Nor in MsSql

    SELECT col1 AS o, e = CASE WHEN o < GETDATE() THEN o ELSE GETDATE() END 
    FROM Table1
    

    Returns:

    Msg 207, Level 16, State 3, Line 1
    Invalid column name 'o'.
    Msg 207, Level 16, State 3, Line 1
    Invalid column name 'o'.
    

    However if I change to CASE WHEN col1... THEN col1 it works

    0 讨论(0)
提交回复
热议问题