如何基于另一列的值SQL在查询中选择创建/添加列?
技术问答
285 人阅读
|
0 人回复
|
2023-09-14
|
我想hook_name根据条件通过SQL选择查询动态添加另一列。$ ~" p9 p0 ]/ d; a
例如,如果hook_type = 0,表hook_name的值应为OFFER,对于hook_type =1,类似的表hook_name应显示“ ACCEPT”。6 I- C; Y4 [$ I
以下是屏幕截图的结果:
8 Y3 d- _% G6 v* ^0 H; [) M: a! P% k* i+ t: E* A! i
查询的选择如下:
" a$ C6 V# Y. ~- e: A; B3 R' M; uselect 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;提前致谢。
7 ~% e4 d: U# ^9 p; E. `" F' h/ s
" ~4 o3 I# o! A3 M$ k6 H$ p) s 解决方案: ( a' Y& T8 q$ C1 a
使用标准的SQL CASE:1 Z, g1 I" m( |. d" G
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 |
|
|
|
|
|