首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

动态日期,按日月统计的有关问题.

2012-08-25 
动态日期,按日月统计的问题...table a(qty, type, datetime)qtytypedatetime3apple07/01/124peach07/15/1

动态日期,按日月统计的问题...
table a(qty, type, datetime); 
qty type datetime
3 apple 07/01/12
4 peach 07/15/12
5 watermelon 09/01/12
........

我现在要按日/月统计水果销售情况,sql如下, 现在存在这样一个问题.
例如: 我要查看 1月到5月的统计情况.但是只有3月和4月有数据. 我其实要显示所有月份的数据.没有的设置为0. 同样的问题存在按日统计里.
我在程序里调用下面的sql,只要传入dateformat(mm/yy, dd/mm/yy) 和 startDate&endDate,一个sql就可以搞定. 
我现在想写一个sql解决我上面提到的问题.如何实现,日期是动态的.
例如: 
1. dateformat='mm/yy', startDate='01/01/12', endDate='10/01/12', 统计1月到10月的所有数据.
2. dateformat='dd/mm/yy', startDate='01/01/12', endDate='02/01/12', 统计1月1号到2月1号的所有数据.

-- 按月/日统计
select sum(nvl(qty,0)) cnt, type, to_char(a.createtime, ':dateformat') 
from a where datetime between :startDate and :endDate
group by type, to_char(a.createtime, ':dateformat');


[解决办法]

SQL code
with t1 as(     select date'2012-03-01' c1,100 c2 from dual     union all     select date'2012-03-14' c1,200 c2 from dual     union all     select date'2012-04-03' c1,300 c2 from dual     union all     select date'2012-04-22' c1,400 c2 from dual)select to_char(a_date,'yyyy-mm') a_date,nvl(sum(c2),0) c2from (select add_months(date'2012-01-01',level-1) a_datefrom dualconnect by level <= 5) a left join t1 b on to_char(a_date,'yyyy-mm') = to_char(c1,'yyyy-mm')group by to_char(a_date,'yyyy-mm')order by a_date      a_date   c2---------------------------1    2012-01    02    2012-02    03    2012-03    3004    2012-04    7005    2012-05    0 

热点排行