decode(to_char(end_date,'MM')-to_char(go_date,'MM'), 
0, trunc(end_date)-trunc(go_date)+1, -- 当月
1, trunc(last_day(go_date))-trunc(go_date)+1,       -- 上月
  trunc(last_day(go_date))-trunc(to_date(to_char(go_date,'YYYYMM'),'YYYYMM')-1)) --上上,上上上....月

解决方案 »

  1.   


    with t as
     (select 'a' name,
             to_date('2014-06-20', 'yyyy-mm-dd') go_date,
             to_date('2014-06-30', 'yyyy-mm-dd') end_date
        from dual
      union all
      select 'a' name,
             to_date('2014-05-28', 'yyyy-mm-dd') go_date,
             to_date('2014-06-03', 'yyyy-mm-dd') end_date
        from dual
      union all
      select 'a' name,
             to_date('2014-06-28', 'yyyy-mm-dd') go_date,
             to_date('2014-06-30', 'yyyy-mm-dd') end_date
        from dual
      union all
      select 'a' name,
             to_date('2014-05-29', 'yyyy-mm-dd') go_date,
             to_date('2014-06-30', 'yyyy-mm-dd') end_date
        from dual
      union all
      select 'b' name,
             to_date('2014-05-29', 'yyyy-mm-dd') go_date,
             to_date('2014-07-02', 'yyyy-mm-dd') end_date
        from dual)
    select name, count(*)
      from (select name, go_date + level - 1 dt, rn
              from (select t.*, rownum rn from t)
            connect by go_date + level <= end_date + 1
                   and prior rn = rn
                   and prior dbms_random.value is not null)
     where to_char(dt, 'mm') = '06'
     group by rn, name;
      

  2.   

    用decode构造一个三值运算把小于/大于 6.1/6.30的天移到6.1/6.30即可,
    select sum(
    decode(sign(to_date('30-jun-14','dd-mm-yy')-end_Date),1,end_date, '30-jun-14')
    -
    decode(sign(go_date-to_date('1-jun-14','dd-mm-yy')),1,go_date, '1-jun-14')
    +1
    )
    from statistics
    where end_Date>='1-jun-14' and go_date<='30-jun-14' and name='a';结果验证正确