by 크크크크크 [SQL Query] PostgreSQL pivot crosstab [2023.08.17 16:17:11]
WITH data AS
(
SELECT 'min' "name", '20230702' "year", 1 "count"
UNION ALL SELECT 'su', '20230702', 3
UNION ALL SELECT 'su', '20230705', 1
UNION ALL SELECT 'su', '20230714', 2
UNION ALL SELECT 'su', '20230726', 7
UNION ALL SELECT 'min', '20230726', 11
UNION ALL SELECT 'min', '20230827', 26
)
SELECT * FROM data
이름은 그대로 나오고 year 날짜가 컬럼으로 가고 그 값은 count로 나타내고 싶습니다..
부탁드립니다.. ㅠㅠ
도무지 어떻게 해야될지 모르겠어요 흑흑...
WITH t_data AS ( SELECT 'min' nm, '20230729' dt, 1 cnt UNION ALL SELECT 'su' , '20230730', 3 UNION ALL SELECT 'su' , '20230731', 1 UNION ALL SELECT 'su' , '20230801', 2 UNION ALL SELECT 'su' , '20230729', 7 UNION ALL SELECT 'min', '20230730', 11 UNION ALL SELECT 'min', '20230801', 26 ) SELECT nm , SUM(CASE dt WHEN '20230729' THEN cnt END) "20230729" , SUM(CASE dt WHEN '20230730' THEN cnt END) "20230730" , SUM(CASE dt WHEN '20230731' THEN cnt END) "20230731" , SUM(CASE dt WHEN '20230801' THEN cnt END) "20230801" FROM t_data WHERE dt >= '20230729' AND dt <= '20230801' GROUP BY nm ;
컬럼값들을 다 알고 있어야 가능합니다.
기간이 변함에 따라 컬럼의 값도 달라지고 개수도 달라진다면?
쿼리만으로는 자동으로 구현되지 않습니다.
동적쿼리를 이용해야 합니다.
WITH t_data AS ( SELECT 'min' nm, '20230702' dt, 1 cnt UNION ALL SELECT 'su' , '20230702', 3 UNION ALL SELECT 'su' , '20230705', 1 UNION ALL SELECT 'su' , '20230714', 2 UNION ALL SELECT 'su' , '20230726', 7 UNION ALL SELECT 'min', '20230726', 11 UNION ALL SELECT 'min', '20230827', 26 ) SELECT nm , SUM(CASE dd WHEN '01' THEN cnt END) m01 , SUM(CASE dd WHEN '02' THEN cnt END) m02 , SUM(CASE dd WHEN '03' THEN cnt END) m03 , SUM(CASE dd WHEN '04' THEN cnt END) m04 , SUM(CASE dd WHEN '05' THEN cnt END) m05 , SUM(CASE dd WHEN '06' THEN cnt END) m06 , SUM(CASE dd WHEN '07' THEN cnt END) m07 , SUM(CASE dd WHEN '08' THEN cnt END) m08 , SUM(CASE dd WHEN '09' THEN cnt END) m09 , SUM(CASE dd WHEN '10' THEN cnt END) m10 , SUM(CASE dd WHEN '11' THEN cnt END) m11 , SUM(CASE dd WHEN '12' THEN cnt END) m12 , SUM(CASE dd WHEN '13' THEN cnt END) m13 , SUM(CASE dd WHEN '14' THEN cnt END) m14 , SUM(CASE dd WHEN '15' THEN cnt END) m15 , SUM(CASE dd WHEN '16' THEN cnt END) m16 , SUM(CASE dd WHEN '17' THEN cnt END) m17 , SUM(CASE dd WHEN '18' THEN cnt END) m18 , SUM(CASE dd WHEN '19' THEN cnt END) m19 , SUM(CASE dd WHEN '20' THEN cnt END) m20 , SUM(CASE dd WHEN '21' THEN cnt END) m21 , SUM(CASE dd WHEN '22' THEN cnt END) m22 , SUM(CASE dd WHEN '23' THEN cnt END) m23 , SUM(CASE dd WHEN '24' THEN cnt END) m24 , SUM(CASE dd WHEN '25' THEN cnt END) m25 , SUM(CASE dd WHEN '26' THEN cnt END) m26 , SUM(CASE dd WHEN '27' THEN cnt END) m27 , SUM(CASE dd WHEN '28' THEN cnt END) m28 , SUM(CASE dd WHEN '29' THEN cnt END) m29 , SUM(CASE dd WHEN '30' THEN cnt END) m30 , SUM(CASE dd WHEN '31' THEN cnt END) m31 FROM (SELECT nm , SUBSTR(dt, 7, 2) dd , cnt FROM t_data WHERE dt LIKE '202307%' ) a GROUP BY nm ;