sql 행을 열로 변환하는 쿼리에 대해 질문드립니다. 0 2 1,249

by tosswin [SQL Query] 쿼리 [2022.10.13 15:03:17]


제가 하고 싶은 내용은 아래와 같습니다.

테이블 A

module_id create_dt o_val
MDL001 2022-10-05 00:00:00 1000
MDL001 2022-10-05 00:15:00 1000
MDL002 2022-10-05 00:00:00 150
MDL002 2022-10-05 00:15:00 150
MDL003 2022-10-05 00:00:00 5
MDL003 2022-10-05 00:15:00 5
MDL004 2022-10-05 00:00:00 800
MDL004 2022-10-05 00:15:00 800
MDL005 2022-10-05 00:00:00 140
MDL005 2022-10-05 00:15:00 140
MDL006 2022-10-05 00:00:00 8
MDL006 2022-10-05 00:15:00 8
MDL007 2022-10-05 00:00:00 700
MDL007 2022-10-05 00:15:00 700
MDL008 2022-10-05 00:00:00 170
MDL008 2022-10-05 00:15:00 170
MDL009 2022-10-05 00:00:00 7
MDL009 2022-10-05 00:15:00 7

 

이러한 테이블을 아래와 같이 시간 기준으로 변경하고 싶습니다.

create_dt col_MDL001 col_MDL002 col_MDL003 col_MDL004 col_MDL005 col_MDL006 col_MDL007 col_MDL008 col_MDL009
2022-10-05 00:00:00 1000 150 5 800 140 8 700 170 7
2022-10-05 00:15:00 1000 150 5 800 140 8 700 170 7

 

어떻게 해야될 지, 이러한 방법도 가능한 지를 몰라서 질문드립니다.

mariadb를 사용하고 있습니다.

by pajama [2022.10.13 15:28:09]

sum case 구문을 사용하시면 됩니다~

select create_dt, 
       sum(case when module_id = 'MDL001' then o_val end) col_MDL001,
	   sum(case when module_id = 'MDL002' then o_val end) col_MDL002,
	   sum(case when module_id = 'MDL003' then o_val end) col_MDL003,
	   sum(case when module_id = 'MDL004' then o_val end) col_MDL004,
	   sum(case when module_id = 'MDL005' then o_val end) col_MDL005,
	   sum(case when module_id = 'MDL006' then o_val end) col_MDL006,
	   sum(case when module_id = 'MDL007' then o_val end) col_MDL007,
	   sum(case when module_id = 'MDL008' then o_val end) col_MDL008,
	   sum(case when module_id = 'MDL009' then o_val end) col_MDL009
from t
group by create_dt

 


by tosswin [2022.10.21 08:59:28]

주신 sql 문으로 잘 되네요.

좋은 방법을 가르쳐주셔서 감사합니다.

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입