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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18312429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:33:34  来源:igfitidea点击:

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

mysqlsqlselect

提问by Ahsan Zaheer

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

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

For example if hook_type = 0, table hook_nameshould have a value of OFFER, and similarly for hook_type = 1, hook_nameshould show "ACCEPT".

例如,如果hook_type = 0, tablehook_name的值应该为OFFER,类似地,对于hook_type = 1hook_name应该显示“接受”。

Below is a screenshot of the result:

下面是结果的截图:

enter image description here

在此处输入图片说明

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.

提前致谢。

回答by dnoeth

Use a Standard SQL CASE:

使用标准 SQL 案例:

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

回答by juergen d

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.

顺便说一句,我认为您想转义列名hook name。然后使用反引号而不是引号。