안녕하세요. 쿼리 질문이 있습니다.
데이터가 아래와 같이 되어있습니다.
seq | member_id | favorite_player |
1 | 0001 | 박지성 |
2 | 0001 | 손흥민 |
3 | 0001 | 이재성 |
4 | 0001 | 황희찬 |
5 | 0001 | 김승규 |
6 | 0002 | 박지성 |
7 | 0002 | 차범근 |
8 | 0002 | 김병지 |
9 | 0003 | 정우영 |
10 | 0004 | 정우영 |
11 | 0004 | 손흥민 |
이렇게 되어있는 데이터를 아래와 같이 표현하고자 합니다.
member_id | plaeyr01 | player02 | player03 | player04 | player05 |
0001 | 박지성 | 손흥민 | 이재성 | 황희찬 | 김승규 |
0002 | 박지성 | 차범근 | 김병지 | null | null |
0003 | 정우영 | null | null | null | null |
0004 | 정우영 | 손흥민 | null | null | null |
쿼리를 어떻게 작성해야 할까요??
-- MSSQL -- WITH t AS ( SELECT 1 seq, '0001' member_id, '박지성' favorite_player UNION ALL SELECT 2, '0001', '손흥민' UNION ALL SELECT 3, '0001', '이재성' UNION ALL SELECT 4, '0001', '황희찬' UNION ALL SELECT 5, '0001', '김승규' UNION ALL SELECT 6, '0002', '박지성' UNION ALL SELECT 7, '0002', '차범근' UNION ALL SELECT 8, '0002', '김병지' UNION ALL SELECT 9, '0003', '정우영' UNION ALL SELECT 10, '0004', '정우영' UNION ALL SELECT 11, '0004', '손흥민' ) -- 1. PIVOT -- SELECT * FROM (SELECT member_id , favorite_player , FORMAT(ROW_NUMBER() OVER(PARTITION BY member_id ORDER BY seq), 'player00') gb FROM t ) a PIVOT (MIN(favorite_player) FOR gb IN ([player01], [player02], [player03], [player04], [player05])) a ; -- 2. GROUP BY, MIN(CASE ) -- SELECT member_id , MIN(CASE rn WHEN 1 THEN favorite_player END) player01 , MIN(CASE rn WHEN 2 THEN favorite_player END) player02 , MIN(CASE rn WHEN 3 THEN favorite_player END) player03 , MIN(CASE rn WHEN 4 THEN favorite_player END) player04 , MIN(CASE rn WHEN 5 THEN favorite_player END) player05 FROM (SELECT member_id , favorite_player , ROW_NUMBER() OVER(PARTITION BY member_id ORDER BY seq) rn FROM t ) a GROUP BY member_id ;