WITH temp AS
(
SELECT '20090316' SDATE, 1 QT, '1' GUBUN, 10000 AMT FROM dual
UNION ALL SELECT '20090316',2, '1', 20000 FROM dual
UNION ALL SELECT '20090316', 3,'2', 10000 FROM dual
UNION ALL SELECT '20090316', 1, '1', 50000 FROM dual
UNION ALL SELECT '20090331', 10, '1', 10 FROM dual
UNION ALL SELECT '20090401', 1, '1', 10 FROM dual
UNION ALL SELECT '20090402',1, '2', 20 FROM dual
)
--원하는 결과는 내역은 모든 row가 나오고 맨오른쪽 컬럼은 차변-대변을 뺀 금액을
계속 합산해서 누계로 표시하고, 중간에 월계,누계가 아래처럼 나오는것인데
월누계는 전월분의 합산으로, 즉 4월의 누계는 3월누계가 누적된 것으로요..
200903 20090316 1 10000 0 10000
200903 20090316 2 20000 0 30000
200903 20090316 3 0 10000 20000
200903 20090316 1 50000 0 70000
200903 20090331 10 10 0 70010
200903 월계 17 80010 10000
200903 누계 17 80010 10000 70010
200904 20090401 1 10 0 70020
200904 20090402 1 0 20 70000
200904 월계 2 10 20
200904 누계 19 80020 10020 70000
SELECT YM,
DECODE(GROUPING(1), 0, NVL(SDATE, YM || '월계'), '누계') SDATE
, DECODE(GROUPING(1), 0, SUM(QT), SUM(SUM(QT)) OVER(PARTITION BY YM ORDER BY YM, SDATE) / 3 ) AS QTY
, DECODE(GROUPING(1), 0, SUM(AMT1) , SUM(SUM(AMT1)) OVER(PARTITION BY YM ORDER BY YM, SDATE) / 3 ) AS AMT1
, DECODE(GROUPING(1), 0, SUM(AMT2) , SUM(SUM(AMT2)) OVER(PARTITION BY YM ORDER BY YM, SDATE) / 3 ) AS AMT2
, SUM(DECODE(GROUPING(SDATE), 0, SUM(NVL(AMT1,0) - NVL(AMT2,0)))) OVER(ORDER BY YM, SDATE) AS NU_AMT
FROM
(
SELECT SUBSTR(SDATE,1,6) YM,
SDATE,
QT,
CASE GUBUN WHEN '1' THEN AMT ELSE 0 END AS AMT1,
CASE GUBUN WHEN '2' THEN AMT ELSE 0 END AS AMT2
FROM temp
)
GROUP BY YM, ROLLUP(1, SDATE)
ORDER BY YM, SDATE
아래처럼 같은 날짜끼리 SUM 되어서 집계되 버리네여,..
원하는 결과를 뽑으러면 어찌해야될까요...? --;
200903 20090316 7 80000 10000 70000
200903 20090331 10 10 0 70010
200903 200903월계 17 80010 10000 70010
200903 누계 17 80010 10000 70010
200904 20090401 1 10 0 70020
200904 20090402 1 0 20 70000
200904 200904월계 2 10 20 70000
200904 누계 2 10 20 70000
|