반응형
DICT, LAST_DAY FUNCTION 사용
dict : dictionary 테이블
1. 등록된 데이터만 나오게 할 경우
SELECT
TO_CHAR(TO_DATE(JRNL_DT,'yyyy-mm-dd'),'dd') AS JRNL_DT,
SUM(TAKEOUT_AMOUNT) AS TAKEOUT_AMOUNT
FROM HCTB_MEDICAL_INJ_PRE
GROUP BY TO_CHAR(TO_DATE(JRNL_DT,'yyyy-mm-dd'),'dd')
EX)
JRNL_DT TAKEOUT_AMOUNT
10 48
11 2
12 1
2. 1~31일 까지 모두 나오게 할때, 데이터가 없는경우 0 ( DICT 테이블을 사용하여 임시로 데이터를 생성한다.)
2.1 UNION ALL 방식
SELECT
JRNL_DT,
SUM(TAKEOUT_AMOUNT) AS TAKEOUT_AMOUNT
FROM(
SELECT
TO_CHAR(TO_DATE(JRNL_DT,'yyyy-mm-dd'),'dd') AS JRNL_DT,
TAKEOUT_AMOUNT
FROM HCTB_MEDICAL_INJ_PRE
UNION ALL
SELECT
DECODE(LENGTH(ROWNUM), 1, '0'||TO_CHAR(ROWNUM), TO_CHAR(ROWNUM)) JRNL_DT,
'' TAKEOUT_AMOUNT
FROM DICT
WHERE ROWNUM <= TO_NUMBER(SUBSTR(LAST_DAY('200902'||'01'), 7, 2))
)
GROUP BY JRNL_DT
ORDER BY JRNL_DT
2.2 LEFT OUTER JOIN 방식
SELECT
A.JRNL_DT,
NVL(B.TAKEOUT_AMOUNT,0) AS TAKEOUT_AMOUNT
FROM
(SELECT
DECODE(LENGTH(ROWNUM), 1, '0'||TO_CHAR(ROWNUM), TO_CHAR(ROWNUM)) JRNL_DT,
0 TAKEOUT_AMOUNT
FROM DICT
WHERE ROWNUM <= TO_NUMBER(SUBSTR(LAST_DAY('200902'||'01'), 7, 2))
)A
LEFT OUTER JOIN
(SELECT
TO_CHAR(TO_DATE(JRNL_DT,'yyyy-mm-dd'),'dd') AS JRNL_DT,
SUM(TAKEOUT_AMOUNT) AS TAKEOUT_AMOUNT
FROM HCTB_MEDICAL_INJ_PRE
GROUP BY TO_CHAR(TO_DATE(JRNL_DT,'yyyy-mm-dd'),'dd')
)B ON(A.JRNL_DT = B.JRNL_DT)
ORDER BY A.JRNL_DT
EX)
JRNL_DT TAKEOUT_AMOUNT
1 0
2 0
3 0
. .
. .
10 48
11 2
12 1
. .
. .
28 0
반응형
'DataBase > oracle' 카테고리의 다른 글
SELECT 로 Query문 만들기 (0) | 2010.04.14 |
---|---|
ORACLE 월별 통계 (1~12월 표현) (2) | 2010.03.15 |
Oracle MERGE INTO(1/2) (0) | 2010.02.07 |
Oracle MERGE INTO(1/1) (0) | 2010.02.07 |
SQL(ORACLE) 여러 행의 특정 컬럼값 -> 하나의 컬럼으로 합치기 (0) | 2010.02.03 |