[퀴즈] 조건부 누적 쿼리
다음과 같은 seq, amt 자료가 있을때 result를 구하는 쿼리를 작성하세요.
순차적으로 amt값을 누적합산하되 그 값이 음수일경우엔 0이 되어야 합니다.
WITH t AS
(
SELECT 1 seq, -2000 amt FROM dual
UNION ALL SELECT 2, 4000 FROM dual
UNION ALL SELECT 3, -5000 FROM dual
UNION ALL SELECT 4, -2000 FROM dual
UNION ALL SELECT 5, 3000 FROM dual
UNION ALL SELECT 6, 1500 FROM dual
UNION ALL SELECT 7, -250 FROM dual
UNION ALL SELECT 8, 320 FROM dual
UNION ALL SELECT 9, -4000 FROM dual
UNION ALL SELECT 10, 10000 FROM dual
UNION ALL SELECT 11, -20000 FROM dual
)
SELECT * FROM t
SEQ AMT RESULT 계산 방법 참고 1 2 3 4 5 6 7 8 9 10 11
-2000
0
-2000 이 음수이므로 0
4000
4000
0 + 4000 = 4000
-5000
0
4000 - 5000 = -1000 = 0
-2000
0
0 - 2000 = -2000 = 0
3000
3000
0 + 3000 = 3000
1500
4500
3000 + 1500 = 4500
-250
4250
4500 - 250 = 4250
320
4570
4250 + 320 = 4570
-4000
570
4570 - 4000 = 570
10000
10570
570 + 10000 = 10570
-20000
0
10570 - 20000 = -9430 = 0
[정답] <=== 트리플클릭
SELECT *
FROM t
MODEL DIMENSION BY (seq)
MEASURES (amt, amt result)
RULES (result[FOR seq FROM 1 TO 11 INCREMENT 1]
= GREATEST(0, SUM(result)[seq BETWEEN CV()-1 AND CV()])
)
;
WITH t AS ( SELECT 1 seq, -2000 amt FROM dual UNION ALL SELECT 2, 4000 FROM dual UNION ALL SELECT 3, -5000 FROM dual UNION ALL SELECT 4, -2000 FROM dual UNION ALL SELECT 5, 3000 FROM dual UNION ALL SELECT 6, 1500 FROM dual UNION ALL SELECT 7, -250 FROM dual UNION ALL SELECT 8, 320 FROM dual UNION ALL SELECT 9, -4000 FROM dual UNION ALL SELECT 10, 10000 FROM dual UNION ALL SELECT 11, -20000 FROM dual ) , t1(seq, amt, result) AS ( SELECT seq, amt , GREATEST(0, amt) result FROM t WHERE seq = 1 UNION ALL SELECT b.seq, b.amt , GREATEST(0, a.result + b.amt) result FROM t1 a, t b WHERE a.seq + 1 = b.seq ) SELECT * FROM t1 ;