3

我的表结构:

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
4

2 回答 2

4

action如果数量已知,这是一个静态查询。

SELECT  cust_id,
        COALESCE(MAX(CASE WHEN action = 'Approved' THEN action_Count END), 0) Approved,
        COALESCE(MAX(CASE WHEN action = 'Pending ' THEN action_Count END), 0) Pending ,
        COALESCE(MAX(CASE WHEN action = 'Rejected' THEN action_Count END), 0) Rejected 
FROM    TableName
GROUP   BY cust_id

但如果值的个数action未知,则更优选动态 sql。

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('COALESCE(MAX(CASE WHEN action = ''',
               action,
               ''' THEN action_Count END), 0) AS ',
               CONCAT('`', action, '`')
               )) INTO @sql
FROM TableName;

SET @sql = CONCAT('SELECT   cust_id, ', @sql, ' 
                    FROM    TableName
                    GROUP   BY cust_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-05-31T05:25:51.373 回答
4

试试这个查询

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

小提琴

| CUST_ID | APPROVED | REJECTED | PENDING |
-------------------------------------------
|       1 |       15 |        6 |       0 |
|       2 |       25 |        7 |      20 |
于 2013-05-31T05:21:11.160 回答