오라클 sql 연습#5

haman92·2022년 9월 9일
0

코드 2개에 대한 월간 집계를 할 때 기간 중복이 있을 경우

ex) 입력값에 대해 7일, 1달, 2달, 3달, 그리고 입력값보다 전인 전체 기간에 대하여 집계하기

select (case when c.level=1 and dt between to_date(:input_dt)-7 and to_date(:input_dt) then '1W'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '1M'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '2M'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '3M'
			 when c.level=1 and dt < to_date(:input_dt)+1 then 'ALL' END)
	  ,t1.code1
	  ,t2.code2
	  ,sum(1)
  from table1 t1
      ,table2 t2
      ,(select level
          from dual
        connect by level<=5) c
 where 1=1
   and t1.a = t2.b
 group by (ase when c.level=1 and dt between to_date(:input_dt)-7 and to_date(:input_dt) then '1W'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '1M'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '2M'
			 when c.level=1 and dt between add_month(to_date(:input_dt) ,-1) and to_date(:input_dt) then '3M'
			 when c.level=1 and dt < to_date(:input_dt)+1 then 'ALL' END), code1 , code2
 
```sql


위와 같이 하면 테이블을 한번 읽고도 집계를 하는 sql을 만들 수 있다.

0개의 댓글