如图SQL2005,这是我的一个数据原表,第一个字段是日,第二个字段为第几周,第三个字段用来合计的。我需要根据第三列,如果是1的汇总后面的金额出来,插入在7和8之间,如果第三列为零的也汇总起来,也插入到7-8之间,大概意思就是7-8之间要插入两行数据。我这个列太多,好像用 with rollup没法实现!create table #temp (id int,week int,weektype int ,weekstr,varchar,amount money)insert into #temp select 1,19,0,'星期日',100 union all  select 2,19,1,'星期一,100 union all select 3,19,1,'星期二',100 union all select 7,19,1,'星期三',100 union all select 5,19,1,'星期四',100 union all select 6,19,0,'星期五',100 union all select 7,19,0,'星期六',100 ...这下面还有很多这样的数据,就是一个月的数据,1-31行。现在每周都要根据第三列汇总出两行数据,最后一周汇总两行外,还要汇总两行所有的总计,这个怎么实现! 我用 with rollup  但需要对ID列进行分组,分组后也不知道怎么汇总,知道的教一下,谢谢,

解决方案 »

  1.   

    不会吧,写这么详细都不明白 ?就是统计汇总行啊。with rollup 
    把第三列为1的amount 列SUM起来添加到7-8行中间。把第三列为0的amount 列也汇总起来插入到7-8行中间
    汇总出两行。
      

  2.   

    select 0, week, weektype, '', sum(amount) from #temp group by week, weektype
      

  3.   

    create table #temp (id int,week int,weektype int ,weekstr varchar(20),amount money)
    insert into #temp
    select 1,19,0,'星期日',100 union all
    select 2,19,1,'星期1',100 union all
    select 3,19,1,'星期2',100 union all
    select 4,19,1,'星期3',100 union all
    select 5,19,1,'星期4',100 union all
    select 6,19,0,'星期5',100 union all
    select 7,19,0,'星期6',100 union all
    select 8,20,0,'星期日',100select * from (
    select * from #temp union all
    select 99999,week,weektype,'合计',amount from 
    (select week,weektype,sum(amount) as amount from #temp group by week,weektype) cte1) cte2
    order by week,idid week weektype weekstr amount
    1 19 0 星期日 100.00
    2 19 1 星期1 100.00
    3 19 1 星期2 100.00
    4 19 1 星期3 100.00
    5 19 1 星期4 100.00
    6 19 0 星期5 100.00
    7 19 0 星期6 100.00
    99999 19 0 合计 300.00
    99999 19 1 合计 400.00
    8 20 0 星期日 100.00
    99999 20 0 合计 100.00