这个就是分组的问题,我用的是sybase数据库,已经测试通过,没有my sql的环境,语法大致都一样,楼主只需要稍微改改就行(以下只是sql查询出的结果没有插入到表)
首先,我建立的数据源表为temp_test
create table temp_test(deptname varchar(100),date_time varchar(100),productcount numeric(20,0));
按月份统计产量的表1实现sql如下:
select deptname 部门,
sum(case when month(date_time)=1 then productcount else 0 end) 一月,
sum(case when month(date_time)=2 then productcount else 0 end) 二月,
sum(case when month(date_time)=3 then productcount else 0 end) 三月,
sum(case when month(date_time)=4 then productcount else 0 end) 四月,
sum(case when month(date_time)=5 then productcount else 0 end) 五月,
sum(case when month(date_time)=6 then productcount else 0 end) 六月,
sum(case when month(date_time)=7 then productcount else 0 end) 七月,
sum(case when month(date_time)=8 then productcount else 0 end) 八月,
sum(case when month(date_time)=9 then productcount else 0 end) 九月,
sum(case when month(date_time)=10 then productcount else 0 end) 十月,
sum(case when month(date_time)=11 then productcount else 0 end) 十一月,
sum(case when month(date_time)=12 then productcount else 0 end) 十二月,
sum(productcount) 合计
from temp_test
group by deptname
按季度统计产量的表2实现的sql如下:
select deptname 部门,
sum(case when month(date_time)>=1 and month(date_time)<=3 then productcount else 0 end) 一季度,
sum(case when month(date_time)>=4 and month(date_time)<=6 then productcount else 0 end) 二季度,
sum(case when month(date_time)>=7 and month(date_time)<=9 then productcount else 0 end) 三季度,
sum(case when month(date_time)>=10 and month(date_time)<=12 then productcount else 0 end) 四季度,
sum(productcount) 合计
from temp_test
group by deptname
[color=green]
注:在sybase里month是获取日期月份的函数;[/color]