Dynamic column alias based on column value

后端 未结 3 1108
时光说笑
时光说笑 2020-12-11 12:42

I want to name the column alias based on the column value in mysql. Is that possible?

Something like this;

select  
  case when answer_type = \'RB\'          


        
相关标签:
3条回答
  • select if(answer_type="RB",true,NULL) as radio, 
    if(answer_type != ="RB",true,NULL) as everything_else
    from XTable;
    

    You have to split them as you get a table for a result where the names or aliases from the select are the column labels. This method lets you check the value of radio (and the value of everything_else) that gets returned.

    What you're trying to do, see there's no way to make the column header work:

    id | radio MAGICAL OR everytning_else |
    1  | RB                               |
    2  | NOT_RB                           |
    

    What my method will do for you:

    id | radio | everything_else |
    1  | true  | NULL            |
    2  | NULL  | true            |
    
    0 讨论(0)
  • 2020-12-11 13:00

    No, that's not possible in pure SQL. You'll probably have to query the data out and then process it in whatever application is executing the query.

    0 讨论(0)
  • 2020-12-11 13:12

    select if(answer_type="RB",'radio',if(answer_type != "RB",'everything_else',NULL)) as answer_type from XTable;

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