[postgresql] rollup 예제 응용 (1) 월 별 합계
ROLLUP 함수
: 그룹 함수 중 하나로, 소그룹 간의 소계를 계산해줌 -> 그룹 함수이기 때문에 GROUP BY 절 안에서 사용.
[postgresql] rollup 활용하여 합계, 소계 명시적으로 나타내기
ROLLUP 함수 : 그룹 함수 중 하나로, 소그룹 간의 소계를 계산해줌 -> 그룹 함수이기때문에 GROUP BY 절 안에서 사용. Preview 1. 전체 합계만 구하기 : group by rollup(( )) /*괄호 두 번*/ 2. 전체 합계 및 소..
jeon-u-jin.tistory.com
예제 응용(1)
- 학원비 결제 TB
school | dept | grade | name | yyyymm | cost |
한양고 | 이과 | 1 | 홍길동 | 202101 | 560000 |
한양고 | 이과 | 1 | 홍길동 | 202102 | 320000 |
한양고 | 문과 | 2 | 현아 | 202101 | 230000 |
한양고 | 문과 | 3 | 김범수 | 202102 | 500000 |
서울고 | 문과 | 1 | 초롱이 | 202101 | 200000 |
서울고 | 문과 | 1 | 초롱이 | 202102 | 200000 |
다음과 같이 학생들이 학원비를 결제한 테이블이 있다. 이 테이블의 소계와 합계를 월별로 나타내면 아래와 같다.
- 소계를 월별로 나타낸 모습
school | dept | grade | m202101 | m202102 |
(null) | 전체합 | (null) | 990000 | 1020000 |
한양고 합 | (null) | (null) | 790000 | 820000 |
한양고 | 이과 합 | (null) | 560000 | 320000 |
한양고 | 이과 | 1 | 560000 | 320000 |
한양고 | 문과 합 | (null) | 230000 | 500000 |
한양고 | 문과 | 2 | 230000 | (null) |
한양고 | 문과 | 3 | (null) | 500000 |
서울고 합 | (null) | (null) | 200000 | 200000 |
서울고 | 문과 합 | (null) | 200000 | 200000 |
서울고 | 문과 | 1 | 200000 | 200000 |
다음과 같은 결과가 나오기 위해서는 크게 두 가지 방법이 있다.
1. decode or case문 사용.
2. 1월과 02월을 join .
1. decode 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
select
*
from(
select
case when school notnull and dept is null and grade is null then concat(school,' 합') else school end school,
case when school is null and grade is null and dept is null then concat(dept,' 전체합')
when dept notnull and grade is null then concat(dept,' 합')
else dept end dept,
grade,
round(sum(decode(yyyymm,'202101',cost))) as m202101,
round(sum(decode(yyyymm,'202102',cost))) as m202102
from
fc_cost
where
yyyymm between '202101' and '202102'
group by rollup (school,dept,grade)
)a
order by
school is null desc ,
school desc,
dept desc
|
- round(sum(decode(yyyymm,'202101',cost))) as m202101
- round(sum(decode(yyyymm,'202102',cost))) as m202102
decode를 이용하여 1월인지 2월인지 구분 후 월별로 합산한다.
2. JOIN을 이용하여 월별 합계를 나타내는 3가지 방법
1. 서브쿼리에서 rollup 후 join
2. 서브 쿼리에 그룹화 후 rollup
3. 서브 쿼리 join 후 rollup
join은 너무 길어져서 다음 포스팅으로...
https://jeon-u-jin.tistory.com/3
[postgresql] rollup 예제 응용(2) - join
지난 포스팅 예제이므로 참고 그룹 함수이기 때문에 GROUP BY 절 안에서 사용. 지난 포스팅 예제의 응용문제이니 참고 그룹 함수이기때문에 GROUP BY 절 안에서 " data-og-host="jeon-u-jin.tistory.com" data-og-..
jeon-u-jin.tistory.com