51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> oracle >> 文章正文

统计每月某个字段总数量的SQL语句

更新时间:2012-3-9:  来源:51代码网

有案件信息表:case_tb 里面有下面几个字段
ajbh 案件编号  
case_date 案发日期  
input_date 录入时间  
foot_num 足迹数量
unit_code 单位代码
   

有单位表:unit_tb 里面有下面几个字段
unit_code unit_name
单位代码 单位名称

需求:要实现的统计功能是根据用户选择的年份,比如2011年,把这一年中每个月单位的足迹数量统计出来

条件:麻烦的就是月的统计时间是从上个月20日开始算起到本月21日止(本月的数据),比如统计2011年1月份的,那就是从2010年12月20日到2011年1月21日,2月份的,那就是从1月20日到2月21日

定义一个计算上个月的函数
create or replace function F_Pre_month(pi_yearmonth in varchar2) return varchar2 is
  Result varchar2(6);
  year number;
  month number;
begin
  year:=to_number(pi_yearmonth,1,4);

  month:=to_number(pi_yearmonth,5,2);
  month:=month-1;
  if(month<=0) then
      month:=12;
      year:=year-1;
  end if;
  Result:=year||lpad(to_char(month),2,'0');
  return(Result);
end F_Pre_month;

然后

select
       2012||lpad(to_char(rownum),2,'0') 月份,
       F_Pre_month(2012||lpad(to_char(rownum),2,'0'))||'20' 起始日期,
       2012||lpad(to_char(rownum),2,'0')||'21' 结束日期
  from dual connect by rownum<=12
可以算出每个月的起始和结束日期
其他的就好处理了
不推荐枚举 反正你的切割点就是每月的20号嘛

select t.createddate,
  to_date(to_char(t.createddate, 'yyyymm') || '20', 'yyyy-mm-dd'),
  case
  when trunc(t.createddate) >
  to_date(to_char(t.createddate, 'yyyymm') || '20', 'yyyy-mm-dd') then
  to_char(add_months(trunc(t.createddate), 1), 'yyyymm')
  else
  to_char(trunc(t.createddate), 'yyyymm')
  end as flag
  from tbo_002 t
一个例子 对数据打上flag

  • 上一篇文章:
  • 下一篇文章: 没有了
  • 赞助商链接
    推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |