일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- Ajax
- Google Map
- rowspan
- jsr 296
- sencha touch
- PLSQL
- JDOM
- PHP
- 선택적조인
- MySQL
- iBATIS
- GPS
- Eclipse
- 가우스
- MFC
- Struts
- Spring
- appspresso
- phonegap
- WebLogic
- JSON
- 전자정부프레임워크
- dock
- Android
- oracle
- ibsheet
- tomcat
- node.js
- swingx
- jQuery
- Today
- Total
Where The Streets Have No Name
UNION,GROUP BY : M:M 및 양쪽 Outer join을 자연스럽게 해결 본문
create table IN_TAB
(CODE varchar2(4),
IN_DATE varchar2(8),
AMOUNT number);
insert into IN_TAB values(1000, '20030101', 1000);
insert into IN_TAB values(1000, '20030101', 6000);
insert into IN_TAB values(1000, '20030103', 2000);
insert into IN_TAB values(1000, '20030104', 7000);
create table OUT_TAB
(CODE varchar2(4),
OUT_DATE varchar2(8),
AMOUNT number);
insert into OUT_TAB values(1000, '20030102', 700);
insert into OUT_TAB values(1000, '20030102', 600);
insert into OUT_TAB values(1000, '20030103', 200);
insert into OUT_TAB values(1000, '20030104', 700);
SELECT CODE, IN_DATE AS DAY, AMOUNT AS IN_AMT, 0 AS OUT_AMT
FROM IN_TAB
UNION ALL
SELECT CODE, OUT_DATE, 0, AMOUNT
FROM OUT_TAB;
CODE | DAY | IN_AMT | OUT_AMT |
---|---|---|---|
1000 | 20030101 | 1000 | 0 |
1000 | 20030101 | 6000 | 0 |
1000 | 20030103 | 2000 | 0 |
1000 | 20030104 | 7000 | 0 |
1000 | 20030102 | 0 | 700 |
1000 | 20030102 | 0 | 600 |
1000 | 20030103 | 0 | 200 |
1000 | 20030104 | 0 | 700 |
SELECT CODE, DAY,
SUM(IN_AMT) AS IN_AMT,
SUM(OUT_AMT) AS OUT_AMT
FROM (SELECT CODE, IN_DATE AS DAY, AMOUNT AS IN_AMT, 0 AS OUT_AMT
FROM IN_TAB
UNION ALL
SELECT CODE, OUT_DATE, 0, AMOUNT
FROM OUT_TAB)
GROUP BY CODE, DAY;
CODE | DAY | IN_AMT | OUT_AMT |
---|---|---|---|
1000 | 20030101 | 7000 | 0 |
1000 | 20030102 | 0 | 1300 |
1000 | 20030103 | 2000 | 200 |
1000 | 20030104 | 7000 | 700 |
-- 조금 더 개선
SELECT CODE, IN_DATE AS DAY, AMOUNT AS IN_AMT, TO_NUMBER(NULL) AS OUT_AMT
FROM IN_TAB
UNION ALL
SELECT CODE, OUT_DATE, TO_NUMBER(NULL), AMOUNT
FROM OUT_TAB;
SELECT CODE, DAY,
SUM(IN_AMT) AS IN_AMT,
SUM(OUT_AMT) AS OUT_AMT
FROM (SELECT CODE, IN_DATE AS DAY, AMOUNT AS IN_AMT, TO_NUMBER(NULL) AS OUT_AMT
FROM IN_TAB
UNION ALL
SELECT CODE, OUT_DATE, TO_NUMBER(NULL), AMOUNT
FROM OUT_TAB)
GROUP BY CODE, DAY;
SELECT CODE, DAY,
NVL(SUM(IN_AMT), 0) AS IN_AMT,
NVL(SUM(OUT_AMT), 0) AS OUT_AMT
FROM (SELECT CODE, IN_DATE AS DAY, AMOUNT AS IN_AMT, TO_NUMBER(NULL) AS OUT_AMT
FROM IN_TAB
UNION ALL
SELECT CODE, OUT_DATE, TO_NUMBER(NULL), AMOUNT
FROM OUT_TAB)
GROUP BY CODE, DAY;