表tb
id,year,month,xun(每个月分 上旬,中旬,下旬), procount(产品数量)
现在的问题是:
  如何根据所选择的年份,查询出每个月上,中和下旬的产品数量统计表
要得到这样的统计列表年份 月份 旬 统计数字
2011 1 上旬 10000 中旬 20000 下旬 13000
2011 2 上旬 11000 中旬 25000 下旬 24000
2011 3 上旬 300 中旬 10000 下旬 50000




2011 12 上旬 5000 中旬 40000 下旬 120000
???

解决方案 »

  1.   

    select year = 2011 , 月份,
           sum(case xun when '上旬' then procount else 0 end) [上旬],
           sum(case xun when '中旬' then procount else 0 end) [中旬],
           sum(case xun when '下旬' then procount else 0 end) [下旬]
    from tb
    where year = 2011
    group by year , 月份
      

  2.   


    declare @表tb table (id int,[year] int,[month] int,xun varchar(4),procount int)
    insert into @表tb
    select 1,2001,1,'上旬',5 union all
    select 2,2001,1,'中旬',5 union all
    select 3,2001,1,'下旬',5 union all
    select 4,2001,2,'上旬',4 union all
    select 5,2001,2,'中旬',7 union all
    select 6,2001,2,'下旬',11 union all
    select 7,2001,3,'上旬',4 union all
    select 8,2001,3,'中旬',9 union all
    select 9,2001,3,'下旬',5select [year],[month],
    数字统计='上旬:'+cast(sum(case xun when '上旬' then procount else 0 end) as varchar(10)),
    数字统计='中旬:'+cast(sum(case xun when '中旬' then procount else 0 end) as varchar(10)),
    数字统计='下旬:'+cast(sum(case xun when '下旬' then procount else 0 end) as varchar(10))
     from @表tb
    group by [year],[month]/*
    year        month       数字统计            数字统计            数字统计
    ----------- ----------- --------------- --------------- ---------------
    2001        1           上旬:5            中旬:5            下旬:5
    2001        2           上旬:4            中旬:7            下旬:11
    2001        3           上旬:4            中旬:9            下旬:5
    */
      

  3.   

    select year = 2011 , 月份,
           sum(case xun when '上旬' then procount else 0 end) [上旬],
           sum(case xun when '中旬' then procount else 0 end) [中旬],
           sum(case xun when '下旬' then procount else 0 end) [下旬],
           sum(case when year = 2011 then procount else 0 end) 总数量
    from tb
    where year = 2011
    group by year , 月份