如何基于另一列的值SQL在查询中选择创建/添加列?
技术问答
321 人阅读
|
0 人回复
|
2023-09-14
|
我想hook_name根据条件通过SQL选择查询动态添加另一列。
. _6 Q; P' y, g' B例如,如果hook_type = 0,表hook_name的值应为OFFER,对于hook_type =1,类似的表hook_name应显示“ ACCEPT”。
; S% S9 D, V4 k9 s, Y以下是屏幕截图的结果:
1 l1 ]8 l7 R1 X" f, S0 c# \% J; L) S& X2 K! E' }! B
查询的选择如下:: {# J2 |7 y: E4 i+ t" p! @
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;提前致谢。+ F7 d2 q1 L" r; }% @ F4 H5 p
1 h' C: X& z* g4 M& U 解决方案:
0 _, w) s# i" [3 b 使用标准的SQL CASE:5 Y( M3 [; f; s) H+ p' d) ^0 c
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 |
|
|
|
|
|