컬럼 타이틀과 개수를 가변으로 하려면 SQL 만으로는 불가능합니다.
동적쿼리로 구현하셔야 합니다.
동적쿼리는 SQL 영역이 아닌 프로그램 영역입니다.
아래 쿼리는 원하는 형태와는 조금 다른 형태의 결과를 도출하는 정적쿼리 구문입니다.
참고하세요.
WITH t1 AS ( SELECT 1000 artc_cd, '202201' evly_yymm, 1 rgst_seq, '부서코드' head_nm UNION ALL SELECT 1000, '202201', 2, '서비스만족도점수' UNION ALL SELECT 1000, '202201', 3, '고객응대점수' UNION ALL SELECT 2000, '202201', 1, '계약번호' UNION ALL SELECT 2000, '202201', 2, '설치일자' UNION ALL SELECT 2000, '202201', 3, '제품번호' UNION ALL SELECT 1000, '202202', 1, '사원번호' UNION ALL SELECT 1000, '202202', 3, '배출점수' UNION ALL SELECT 2000, '202202', 1, '부서코드' UNION ALL SELECT 2000, '202202', 2, '사원번호' UNION ALL SELECT 2000, '202202', 3, '판매실적건수' UNION ALL SELECT 2000, '202202', 4, '서비스만족도점수' UNION ALL SELECT 3000, '202202', 1, '사원번호' UNION ALL SELECT 3000, '202202', 2, '인정건수' ) , t2 AS ( SELECT 1000 artc_cd, '202201' evly_yymm, 5 rgst_seq, 'A1' aply_val1, '80' aply_val2, '40' aply_val3, null aply_val4, null aply_val5, null aply_val6 UNION ALL SELECT 1000, '202201', 6, 'B1' , '70' , '70' , null, null, null UNION ALL SELECT 2000, '202201', 7, '202201_01', '20220110', 'A3456', null, null, null UNION ALL SELECT 2000, '202201', 8, '202201_02', '20220120', 'B1234', null, null, null UNION ALL SELECT 1000, '202202', 9, '100001' , null , '40' , null, null, null UNION ALL SELECT 1000, '202202', 10, '100002' , null , '60' , null, null, null UNION ALL SELECT 1000, '202202', 11, '100003' , null , '90' , null, null, null UNION ALL SELECT 2000, '202202', 12, 'A1' , '100001' , '200' , '90', null, null UNION ALL SELECT 2000, '202202', 13, 'A1' , '100002' , '150' , '85', null, null UNION ALL SELECT 3000, '202202', 14, '100001' , '20' , NULL , null, null, null ) , copy_t AS ( SELECT 1 seq UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 ) SELECT artc_cd , evly_yymm , rgst_seq , MIN(CASE rn WHEN 1 THEN v END) v1 , MIN(CASE rn WHEN 2 THEN v END) v2 , MIN(CASE rn WHEN 3 THEN v END) v3 , MIN(CASE rn WHEN 4 THEN v END) v4 , MIN(CASE rn WHEN 5 THEN v END) v5 , MIN(CASE rn WHEN 6 THEN v END) v6 FROM (SELECT a.artc_cd , a.evly_yymm , 0 rgst_seq , ROW_NUMBER() OVER(ORDER BY a.rgst_seq) rn , head_nm v FROM t1 a WHERE a.artc_cd = 1000 AND a.evly_yymm = '202202' UNION ALL SELECT artc_cd , evly_yymm , rgst_seq , DENSE_RANK() OVER(ORDER BY seq) rn , v FROM (SELECT a.artc_cd , a.evly_yymm , b.seq , a.rgst_seq , CAST( CASE b.seq WHEN 1 THEN a.aply_val1 WHEN 2 THEN a.aply_val2 WHEN 3 THEN a.aply_val3 WHEN 4 THEN a.aply_val4 WHEN 5 THEN a.aply_val5 WHEN 6 THEN a.aply_val6 END AS VARCHAR(99)) v FROM t2 a CROSS JOIN (SELECT seq FROM copy_t WHERE seq <= 6) b WHERE a.artc_cd = 1000 AND a.evly_yymm = '202202' ) a WHERE v IS NOT NULL ) a GROUP BY artc_cd, evly_yymm, rgst_seq ;