실습용 테이블 생성
CREATE TABLE COPY_T
AS
SELECT LEVEL AS NO,To_char(LEVEL,'09') AS NO2
FROM DUAL
CONNECT BY LEVEL <= 31;
CREATE TABLE TAB1 (
ITEM CHAR(1) NOT NULL,SEQ NUMBER NOT NULL,AMT NUMBER NULL,YMD VARCHAR(8) NULL);
CREATE UNIQUE INDEX XPKTAB1 ON TAB1 (
ITEM ASC,
SEQ ASC);
ALTER TABLE TAB1
ADD CONSTRAINT XPKTAB1 PRIMARY KEY ( ITEM,SEQ );
CREATE TABLE TAB2 (
ITEM CHAR(1) NULL,AMT NUMBER NULL,YM VARCHAR(6) NULL);
INSERT INTO TAB1
(SELECT 'A',1,100,'20090301' FROM DUAL
UNION ALL
SELECT 'A',2,200,'20090305' FROM DUAL
UNION ALL
SELECT 'A',3,150,'20090301' FROM DUAL
UNION ALL
SELECT 'B',1,100,'20090302' FROM DUAL
UNION ALL
SELECT 'B',2,120,'20090305' FROM DUAL
UNION ALL
SELECT 'B',3,200,'20090312' FROM DUAL
UNION ALL
SELECT 'D',1,100,'20090303' FROM DUAL
UNION ALL
SELECT 'D',2,300,'20090307' FROM DUAL
UNION ALL
SELECT 'D',3,200,'20090311' FROM DUAL);
INSERT INTO TAB2
(SELECT 'A',250,'200903' FROM DUAL
UNION ALL
SELECT 'C',300,'200903' FROM DUAL
UNION ALL
SELECT 'D',500,'200903' FROM DUAL
UNION ALL
SELECT 'A',200,'200903' FROM DUAL);
원하는 결과
ITEM | SQE | TAB1_AMT | TAB2_AMT | 차이 |
---|---|---|---|---|
A | TOT | 450 | 450 | 0 |
1 | 100 | |||
2 | 200 | |||
3 | 150 | |||
B | TOT | 420 | 420 | |
1 | 100 | |||
2 | 120 | |||
3 | 200 | |||
C | TOT | 300 | -300 | |
D | TOT | 600 | 500 | 100 |
1 | 100 | |||
2 | 300 | |||
3 | 200 |
조회 쿼리
SELECT min(decode(No, 1, item)) ITEM,
min(decode(No, 1, 'TOT', seq)) SEQ,
sum(decode(sw, 0, amt)) TAB1_AMT,
sum(decode(sw, 2, amt)) TAB2_AMT,
sum((1-sw)*decode(No, 1, amt)) 차이
FROM (SELECT item, No, decode(No, 1, 'TOT', seq) seq, sum(amt) amt, 0 sw
FROM (SELECT item, seq, amt
FROM TAB1
WHERE ymd like '200903%') x, COPY_T y
WHERE y.No <= 2
GROUP BY item, No, decode(No, 1, 'TOT', seq)
UNION ALL
SELECT item, 1 No, 'TOT' seq, amt, 2 sw
FROM TAB2
WHERE ym = '200903') a
GROUP BY item, No, seq
ORDER BY a.item, No, seq