조회 데이터에 대한 문의입니다. 아래 보시는 "데이터"를 아래 보이는 "To-BE) 조회값" 처럼 쿼리를 생성하고 싶습니다. 행으로 표현된 금액값을 열로 표현하려면 어떻게 해야 좋을까요? ^^ * 데이터 SELECT '1' AS cnt, '01' AS code, '100' AS amt FROM DUAL UNION ALL SELECT '1' AS cnt, '02' AS code, '200' AS amt FROM DUAL UNION ALL SELECT '1' AS cnt, '03' AS code, '300' AS amt FROM DUAL UNION ALL SELECT '2' AS cnt, '01' AS code, '10' AS amt FROM DUAL UNION ALL SELECT '2' AS cnt, '02' AS code, '20' AS amt FROM DUAL UNION ALL SELECT '2' AS cnt, '03' AS code, '30' AS amt FROM DUAL ;
* AS-IS) 조회값
cnt | code | amt |
1 | 01 | 100 |
1 | 02 | 200 |
1 | 03 | 300 |
2 | 01 | 10 |
2 | 02 | 20 |
2 | 03 | 30 |
* To-BE) 조회값
amt1 | amt2 | amt3 |
100 | 200 | 300 |
10 | 20 | 30 |
마농님 말씀처럼 묶이는 명확한 근거가 있어야 하겠지만...
일단 무조건 3 Row씩 자른다면...다음과 같이 해보았습니다.
WITH TMP AS ( SELECT '1' AS cnt, '01' AS code, '100' AS amt FROM DUAL UNION ALL SELECT '2' AS cnt, '02' AS code, '200' AS amt FROM DUAL UNION ALL SELECT '3' AS cnt, '03' AS code, '300' AS amt FROM DUAL UNION ALL SELECT '4' AS cnt, '01' AS code, '10' AS amt FROM DUAL UNION ALL SELECT '5' AS cnt, '02' AS code, '20' AS amt FROM DUAL UNION ALL SELECT '6' AS cnt, '03' AS code, '30' AS amt FROM DUAL UNION ALL SELECT '8' AS cnt, '01' AS code, '15' AS amt FROM DUAL UNION ALL SELECT '9' AS cnt, '02' AS code, '25' AS amt FROM DUAL UNION ALL SELECT '11' AS cnt, '03' AS code, '35' AS amt FROM DUAL ) SELECT * FROM (SELECT TRUNC((ROWNUM-1)/ 3) GUBUN, code, amt FROM TMP) PIVOT(SUM(amt) FOR code IN('01' AS AMT1, '02' AS AMT2, '03' AS AMT3)) ORDER BY GUBUN ;
애초에 예시를 잘 못 들어서 일어난 일이네요.
그룹 기준이 명확하게 있었네요.
WITH t AS ( SELECT 1 cnt, '01' code, 100 amt FROM dual UNION ALL SELECT 1, '02', 200 FROM dual UNION ALL SELECT 1, '03', 300 FROM dual UNION ALL SELECT 2, '01', 10 FROM dual UNION ALL SELECT 2, '02', 20 FROM dual UNION ALL SELECT 2, '03', 30 FROM dual ) SELECT * FROM t PIVOT (MIN(amt) FOR code IN ('01' amt1, '02' amt2, '03' amt3)) ;