如何根据其他列值在sql select查询中创建/添加列

时间:2022-01-20 13:41:02

I want to dynamically add another column "hook_name", via a select SQL query, based on condition, For example if hook_type=0, table hook_name should have a value of "OFFER", similarly for hook_type=1, hook_name should show "ACCEPT".

我想根据条件通过select SQL查询动态添加另一列“hook_name”,例如,如果hook_type = 0,表hook_name应该具有值“OFFER”,类似于hook_type = 1,hook_name应该显示“ACCEPT” ”。

Below is the screenshot of the result.

以下是结果的屏幕截图。

http://imgur.com/DY9rQBx

The select query is this.

选择查询是这样的。

select hook_type, 'hook name' as hook_name,
       count(*) as number_of_exchange_activities 
from `exchange` 
group by hook_type # hook_type 0 for OFFER, 1 for ACCEPT and 2 for offer EXPIRED;

Thanks in advance.

提前致谢。

2 个解决方案

#1


11  

Use a Standard SQL CASE:

使用标准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

#2


5  

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.

BTW我想你想要转义列名钩子名称。然后使用反引号而不是引号。

#1


11  

Use a Standard SQL CASE:

使用标准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

#2


5  

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.

BTW我想你想要转义列名钩子名称。然后使用反引号而不是引号。