长沙震烨科技有限公司 专注研发高校招生考试系统

oracle 实现按天,周,月,季度,年查询统计数据

2016/7/6 11:54:26 人评论 次浏览 分类:其他

这里提供了一种方法,挺不错oracle 实现按周,月,季度,年查询统计数据 。

还在网上看到用trunc来搞也可以,下面是个例子,两句SQL效果一样的.
id有重复的,所以group by搞了两个字段.
只在Oracle数据库里试过,其它库没试过。

view source print ?
1  create table CONSUMER_ACC 

2  ( 

3  ID VARCHAR2(50) not null , 

4  ACC_NUM VARCHAR2(10), 

5  DATETIME DATE 

6  ) 

view source print ?
01  select t.id,trunc(t.datetime, 'mm' ) as d, sum (t.acc_num) as n 

02  from CONSUMER_ACC t 

03  --where 

04  group by t.id,trunc(t.datetime, 'mm' ) 

05  order by n desc ; 

06  

07  select t.id,to_char(t.datetime, 'mm' ) d , sum (t.acc_num) n 

08  from CONSUMER_ACC t 

09  --where 

10  group by t.id,to_char(t.datetime, 'mm' ) 

11  order by n desc 
------------------------------------------------------------------------------

  1. //按天统计   
  2. select count(dataid) as 每天操作数量, sum()  
  3. from  
  4. where  
  5. group by trunc(createtime, 'DD'))  
  6. //按自然周统计    
  7. select to_char(date,'iw'),sum()   
  8. from   
  9. where   
  10. group by to_char(date,'iw')   
  11. //按自然月统计    
  12. select to_char(date,'mm'),sum()   
  13. from   
  14. where   
  15. group by to_char(date,'mm')   
  16. //按季统计    
  17. select to_char(date,'q'),sum()   
  18. from   
  19. where   
  20. group by to_char(date,'q')   
  21. //按年统计    
  22. select to_char(date,'yyyy'),sum()   
  23. from   
  24. where   
  25. group by to_char(date,'yyyy'

附件下载