How to create/add a column in an SQL select query based on another column's values?

后端 未结 2 892
北荒
北荒 2021-02-01 07:50

I want to dynamically add another column hook_name, via an SQL select query, based on a condition.

For example if hook_type = 0, table ho

相关标签:
2条回答
  • 2021-02-01 08:42
    select case when hook_type = 0 then 'offer'
                when hook_type = 1 then 'accept'
                else 'expired'
           end as hook_t, 
          `hook name` as hook_name,
          count(*) as number_of_exchange_activities 
    from `exchange` 
    group by hook_t
    

    BTW I think you want to escape the column name hook name. Then use backticks and not quotes.

    0 讨论(0)
  • 2021-02-01 08:43

    Use a Standard SQL CASE:

    SELECT hook_type, 
       CASE hook_type
          WHEN 0 THEN 'OFFER'
          WHEN 1 THEN 'ACCEPT'
          WHEN 2 THEN 'EXPIRED'
       END AS hook_name,
       COUNT(*) AS number_of_exchange_activities 
    FROM `exchange` 
    GROUP BY hook_type
    
    0 讨论(0)
提交回复
热议问题