急求一条统计一年每个月某个字段总数量的SQL语句,条件有点特殊
请问这个统计的SQL语句该怎么写?
[解决办法]
不知道能不能通过这样的方式来连接?
SELECT add_months(ADD_MONTHS(DATE'2010-12-01',LEVEL)+19,-1) AS COL1
FROM DUAL
CONNECT BY LEVEL <= 12
COL1
--------------------------
12010/12/20
22011/1/20
32011/2/20
42011/3/20
52011/4/20
62011/5/20
72011/6/20
82011/7/20
92011/8/20
102011/9/20
112011/10/20
122011/11/20
[解决办法]
定义一个计算上个月的函数
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
可以算出每个月的起始和结束日期
其他的就好处理了
[解决办法]
select code,case monthNum when 1 then total else 0 end as month1,
case monthNum when 2 then total else 0 end as month2,
case monthNum when 3 then total else 0 end as month3,
case monthNum when 4 then total else 0 end as month4,
case monthNum when 5 then total else 0 end as month5,
case monthNum when 6 then total else 0 end as month6,
case monthNum when 7 then total else 0 end as month7,
case monthNum when 8 then total else 0 end as month8,
case monthNum when 9 then total else 0 end as month9,
case monthNum when 10 then total else 0 end as month10,
case monthNum when 11 then total else 0 end as month11,
case monthNum when 12 then total else 0 end as month12
from (
select code,case when to_char(inputDate,'dd')>20 then to_char(inputDate,'mm') + 1 else to_char(inputDate,'mm') as monthNum ,sum(num) as total from tableName
)
[解决办法]
不推荐枚举 反正你的切割点就是每月的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
