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

有案件信息表: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值