我的表结构:

cust_id | action   | action_count
--------+----------+-------------
1       | Approved | 15
2       | Approved | 25
1       | Rejected | 6
2       | Pending  | 20
2       | Rejected | 7

我必须得到查询结果为:
cust_id | Approved | Pending | Rejected
--------+----------+---------+---------
1       | 15       | 0       | 6
2       | 25       | 20      | 7

最佳答案

试试这个查询

select
   cust_id,
   max(if(action='Approved', action_count, 0)) as Approved,
   max(if(action='Rejected', action_count, 0)) as Rejected,
   max(if(action='Pending', action_count, 0)) as Pending
from
   tbl
group by
   cust_id

FIDDLE
| CUST_ID | APPROVED | REJECTED | PENDING |
-------------------------------------------
|       1 |       15 |        6 |       0 |
|       2 |       25 |        7 |      20 |

关于mysql - 将行作为列查询 (MySQL),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16850214/

10-10 02:47