SQL: Alias Column Name for Use in CASE Statement

前端 未结 11 1776
悲哀的现实
悲哀的现实 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: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;
    

提交回复
热议问题