双能太阳能,奥特朗热水器 2011-12-26 14:57
浏览 263
已采纳

(新年快乐!)请问高手: 如何写如下SQL语句。多谢!

源数据表: 部门 日期 产量
A 2011-01-02 100
B 2011-04-23 20
A 2011-09-01 15
A 2011-05-01 10
A 2011-11-01 30

现想产生
表1:

按月份统计产量: 部门 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月 合计

             A      100               10                    15         30           155
             B                    20                                                 20

表2:
按季度统计产量: 部门 1季度 2季度 3季度 4季度 合计

             A      100        10          15          30        155
             B                 20                                 20

请问大侠您: 如何写MS SQL 语句从源数据表产生表1 和表2?

多谢!
祝大家新年快乐!万事如意!

  • 写回答

3条回答 默认 最新

  • lzz7658823 2011-12-26 16:31
    关注

    这个就是分组的问题,我用的是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]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?