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
How to create/add a column in an SQL select query based on another column's values?
提问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_name
should have a value of OFFER
, and similarly for hook_type = 1
, hook_name
should show "ACCEPT".
例如,如果hook_type = 0
, tablehook_name
的值应该为OFFER
,类似地,对于hook_type = 1
,hook_name
应该显示“接受”。
Below is a screenshot of the result:
下面是结果的截图:
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
。然后使用反引号而不是引号。