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

このクエリを試してください

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 に答える
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 に答える