将行查询为列(MySQL)

时间:2013-05-31 05:16:13

标签: mysql sql

我的表结构:

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

2 个答案:

答案 0 :(得分: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

FIDDLE

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

答案 1 :(得分: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;