[퀴즈] 분석함수의 이해
구분1, 구분2, 날짜, 값으로 구성된 테이블이 있습니다.
구분1, 구분2 그룹으로 최종날짜와 금액합계를 구하고,
구분1별 최종날짜와 그에 해당하는 구분2값과 금액합계를 구하시오.
WITH t AS
(
SELECT 'A' gb1, '01' gb2, '20100601' dt, 10 v FROM dual
UNION ALL SELECT 'A', '01', '20100604', 20 FROM dual
UNION ALL SELECT 'A', '02', '20100603', 30 FROM dual
UNION ALL SELECT 'A', '03', '20100602', 40 FROM dual
UNION ALL SELECT 'B', '01', '20100601', 50 FROM dual
UNION ALL SELECT 'B', '02', '20100605', 60 FROM dual
UNION ALL SELECT 'B', '03', '20100603', 70 FROM dual
UNION ALL SELECT 'B', '04', '20100602', 80 FROM dual
)
SELECT * FROM t
;
[원본]
[결과]
GB1
GB2
DT
V
GB1
GB2
DT
V
MAX_DT
MAX_DT_GB2
MAX_DT_V
A
01
20100601
10
A
01
20100604
30
20100604
01
30
A
01
20100604
20
A
02
20100603
30
20100604
01
30
A
02
20100603
30
A
03
20100602
40
20100604
01
30
A
03
20100602
40
B
01
20100601
50
20100605
02
60
B
01
20100601
50
B
02
20100605
60
20100605
02
60
B
02
20100605
60
B
03
20100603
70
20100605
02
60
B
03
20100603
70
B
04
20100602
80
20100605
02
60
B
04
20100602
80
정답은 몇일 뒤 다시 올리겠습니다.
[정답] <=== 트리플클릭
SELECT gb1
, gb2
, MAX(dt) dt
, SUM(v) v
, MAX(MAX(dt)) OVER(PARTITION BY gb1) max_dt
, MAX(gb2) KEEP(DENSE_RANK LAST ORDER BY MAX(dt)) OVER(PARTITION BY gb1) max_dt_gb2
, MAX(SUM(v)) KEEP(DENSE_RANK LAST ORDER BY MAX(dt)) OVER(PARTITION BY gb1) max_dt_v
FROM t
GROUP BY gb1, gb2
ORDER BY gb1, gb2
;