以列形式查询行(MySQL)
我的表格结构:以列形式查询行(MySQL),mysql,sql,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
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
如果
操作
的数量已知,这里有一个静态查询
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;
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;