物料代码  客户名称   数量  单价  金额   期间
A001      文冲学校    10   10    100    1
A002      造船厂      8    12    96     2
A001      文冲学校    12   8     96     1
B001      文冲学校    10   10    100    1
B002      造船厂      8    12    96     2
B001      文冲学校    12   8     96     1
.....
想得到如下结果:
物料代码  客户名称     单价 数量  金额  
A001      文冲学校     10   10    100    
A002      造船厂       8    12    96     
A001      文冲学校     12   8     96     
          A物料合计         30    292
         292
B001      文冲学校     10   10    100    
B004      造船厂       8    12    96     
B001      文冲学校     12   8     96     
          B物料合计         30   292
          .....
          物料合计          60   584    急急!!

解决方案 »

  1.   

    create table tb(code nvarchar(20),name nvarchar(20),num int,price int,tmoney int,tdate int)
    insert into tb select 'A001',N'文冲中学',10,10,100,1
         union all select 'A002',N'造船厂',  8, 12,96, 2
         union all select 'A001',N'文冲中学',12, 8,96, 1
         union all select 'B001',N'文冲中学',10, 10,100, 1
         union all select 'B002',N'造船厂',  8, 12,96, 2
         union all select 'B001',N'文冲中学',12, 8,96, 1
    select * from tb where code like 'A%'
    union all
    select 'A物料合计','',sum(num),sum(price),sum(tmoney),sum(tdate) from tb where code like 'A%'
    union all
    select * from tb where code like 'B%'
    union all
    select 'B物料合计','',sum(num),sum(price),sum(tmoney),sum(tdate) from tb where code like 'B%'drop table tb----------------------------------
    A001 文冲中学 10 10 100 1
    A002 造船厂 8 12 96 2
    A001 文冲中学 12 8 96 1
    A物料合计 30 30 292 4
    B001 文冲中学 10 10 100 1
    B002 造船厂 8 12 96 2
    B001 文冲中学 12 8 96 1
    B物料合计 30 30 292 4
      

  2.   

    create table #t(ID varchar(4),CustomID nvarchar(20),Qty int,price decimal(18,2),sumMoney decimal(18,2),period int)
    insert into #t
    select 'A001',      '文冲学校',10,10,100,1 union all
    select 'A002',      '造船厂',    8,   12,    96,    2 union all
    select 'B001',      '文冲学校',    10,   10,    100,    1 union all
    select 'B002',      '造船厂',    8,   12,    96,    2 
    go
    select case when grouping(CustomID)=1 then '' else max(id) end,
           case when grouping(CustomID)=1 and grouping(substring(ID,1,1))=0 then substring(max(ID),1,1)+'物料合计' 
                when grouping(CustomID)=1 and grouping(substring(ID,1,1))=1 then '物料合计' else CustomID end,
           sum(qty),sum(price),sum(sumMoney),sum(period) 
    from #t 
    group by substring(ID,1,1),CustomID with rollupDROP table #t