如何根据另一列的值在SQL select查询中创建/添加列?

时间:2013-08-19 11:14:20

标签: mysql sql select

我想根据条件通过SQL select查询动态添加另一列hook_name

例如,如果hook_type = 0,则表格hook_name的值应为OFFER,而对于hook_type = 1类似,hook_name应显示“接受”。< / p>

以下是结果的屏幕截图:

enter image description here

选择查询是:

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;

提前致谢。

2 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:6)

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我想你想要转义列名hook name。然后使用反引号而不是引号。