Thursday, March 27, 2008

Select between dates in Oracle SQL

SQL> with t as (select to_date('01/01/2007','dd/mm/yyyy') as update_date from dual union all
2 select to_date('01/01/2007','dd/mm/yyyy') from dual union all
3 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
4 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
5 select to_date('03/01/2007','dd/mm/yyyy') from dual union all
6 select to_date('04/01/2007','dd/mm/yyyy') from dual union all
7 select to_date('05/01/2007','dd/mm/yyyy') from dual union all
8 select to_date('07/01/2007','dd/mm/yyyy') from dual union all
9 select to_date('07/01/2007','dd/mm/yyyy') from dual)
10 -- end of test data
11 select to_char(x.UPDATE_DATE, 'YYYY-MM-DD') as update_date, DECODE(t.update_date, NULL, 0, count (*)) as count
12 from (select to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')+(rownum-1) as update_date
13 from dual
14 connect by rownum <= (to_date('2007-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS') -
15 to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS'))) x
16 LEFT OUTER JOIN t ON (x.update_date = t.update_date)
17 where x.UPDATE_DATE >= to_date('2007-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
18 and x.UPDATE_DATE < color="navy">'2007-02-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')
19 group by to_char(x.UPDATE_DATE, 'YYYY-MM-DD'), t.update_date
20 order by 1
21 /

UPDATE_DAT COUNT
---------- ----------
2007-01-01 2
2007-01-02 0
2007-01-03 3
2007-01-04 1
2007-01-05 1

No comments: