繁体   English   中英

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

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

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

例如,如果hook_type = 0 ,则表hook_name的值应为OFFER ,类似于hook_type = 1hook_name应显示“ACCEPT”。

以下是结果的屏幕截图:

在此输入图像描述

选择查询是这样的:

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;

提前致谢。

使用标准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
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 然后使用反引号而不是引号。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM