행을 열로 변환하는 쿼리 도움주세요. 2

by 이우민 [SQL Query] [2025.04.09 08:50:31]


행을 열로 변환하는 쿼리 도움주세요. 그리고 최근 3건만요

예) 

 

사번 수강일 과목 내용
A 20250101 영어 11
A 20250103 수학 22
A 20250102 국어 33
A 20250104 과학 44
B 20250101 영어 55
B 20250102 국어 66

 

 

결과

사번 과목1 내용1 과목2 내용2 과목3 내용3
A 과학 44 수학 22 국어 33
B 국어 66 영어 55    

이렇게요.... 

감사합니다. 

 

by 우주민 [2025.04.09 09:19:48]
with table_a as 
(
select 'A' as 사번, '20250101' as 수강일, '영어' as 과목, '11' as 내용 union all
select 'A' as 사번, '20250103' as 수강일, '수학' as 과목, '22' as 내용 union all
select 'A' as 사번, '20250102' as 수강일, '국어' as 과목, '33' as 내용 union all
select 'A' as 사번, '20250104' as 수강일, '과학' as 과목, '44' as 내용 union all
select 'B' as 사번, '20250101' as 수강일, '영어' as 과목, '55' as 내용 union all
select 'B' as 사번, '20250102' as 수강일, '국어' as 과목, '66' as 내용 
)
select 사번
     , max(case when rn = 1 then 과목 end) as 과목1
     , max(case when rn = 1 then 내용 end) as 내용1
     , max(case when rn = 2 then 과목 end) as 과목2
     , max(case when rn = 2 then 내용 end) as 내용2
     , max(case when rn = 3 then 과목 end) as 과목3
     , max(case when rn = 3 then 내용 end) as 내용3
  from (select 사번, 과목, 내용
             , row_number() over(partition by 사번 order by 수강일 desc) as rn
          from table_a
       ) t
 group by 사번
 order by 사번

 


by 이우민 [2025.04.09 09:44:25]

with 절에 테이블명

from dual  을 넣으니 잘됩니다. 감사합니다. 

 

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