PIVOT 쿼리 질문이 있습니다.
데이터가 아래와 같이 있습니다.
USER_NO | TEAM | TOTAL_AMOUNT | TOTAL_QTY | VISIT_CNT |
AAA | TEAM_A | 10000 | 2 | 1 |
AAA | TEAM_B | 20000 | 1 | 1 |
AAA | TEAM_C | 0 | 0 | 0 |
AAA | TEAM_D | 0 | 0 | 0 |
BBB | TEAM_A | 20000 | 4 | 2 |
BBB | TEAM_B | 0 | 0 | 0 |
BBB | TEAM_C | 0 | 0 | 0 |
BBB | TEAM_D | 0 | 0 | 0 |
이렇게 되어있는 데이터를 PIVOT 또는 다른 쿼리를 이용하여 아래표와 같이 표현하고 싶습니다.
USER_NO | TEAM_A (TOTAL_AMOUNT) | TEAM_A (TOTAL_QTY) | TEAM_A (VISIT_CNT) | TEAM_B (TOTAL_AMOUNT) | TEAM_B (TOTAL_QTY) | TEAM_B (VISIT_CNT) | ...... |
AAA | 10000 | 2 | 1 | 20000 | 1 | 1 | ... |
BBB | 20000 | 4 | 2 | 0 | 0 | 0 | ... |
이렇게 열로 되어있는 것을 행으로 변경하고 싶습니다.
어떻게 쿼리를 만들어야 할까요?
WITH t AS ( SELECT 'AAA' user_no, 'TEAM_A' team, 10000 total_amount, 2 total_qty, 1 visit_cnt UNION ALL SELECT 'AAA', 'TEAM_B', 20000, 1, 1 UNION ALL SELECT 'AAA', 'TEAM_C', 0, 0, 0 UNION ALL SELECT 'AAA', 'TEAM_D', 0, 0, 0 UNION ALL SELECT 'BBB', 'TEAM_A', 20000, 4, 2 UNION ALL SELECT 'BBB', 'TEAM_B', 0, 0, 0 UNION ALL SELECT 'BBB', 'TEAM_C', 0, 0, 0 UNION ALL SELECT 'BBB', 'TEAM_D', 0, 0, 0 ) SELECT user_no , SUM(CASE team WHEN 'TEAM_A' THEN total_amount END) amt_A , SUM(CASE team WHEN 'TEAM_A' THEN total_qty END) qty_A , SUM(CASE team WHEN 'TEAM_A' THEN visit_cnt END) cnt_A , SUM(CASE team WHEN 'TEAM_B' THEN total_amount END) amt_B , SUM(CASE team WHEN 'TEAM_B' THEN total_qty END) qty_B , SUM(CASE team WHEN 'TEAM_B' THEN visit_cnt END) cnt_B , SUM(CASE team WHEN 'TEAM_C' THEN total_amount END) amt_C , SUM(CASE team WHEN 'TEAM_C' THEN total_qty END) qty_C , SUM(CASE team WHEN 'TEAM_C' THEN visit_cnt END) cnt_C , SUM(CASE team WHEN 'TEAM_D' THEN total_amount END) amt_D , SUM(CASE team WHEN 'TEAM_D' THEN total_qty END) qty_D , SUM(CASE team WHEN 'TEAM_D' THEN visit_cnt END) cnt_D FROM t GROUP BY user_no ;