表:
箱号(BoxId)   物料类型(Tno)   物料编号(Bno) 数量(Qty) 净重(netweight)  毛重(GrossWeight)
A4               T1            B001           2000     6.80kg               8.12kg
A4               T2            B002           4000      null                  null 
A5               T3            B003           5000     6.70kg               7.04kg   
A6               T3            B004           4500     5.50kg               6.56kg如上表,每一箱都有净重和毛重,而且相同的箱只输入一次净重和毛重,比如A4箱有两个物料类型,A5,A6只装了一种物料类型
要求统计每种物料的总重量(是按照数量比去统计的,比如T1的净重量应该是 2000/(2000+4000)*6.8,T2的净重量是4000/(2000+4000)*6.8,T3的净重就是6.70+5.5了),毛重原理一样。请问这个SQL该怎么写

解决方案 »

  1.   

    --建立测试环境
    set nocount on
    create table test(箱号 varchar(20),物料类型 varchar(20),物料编号 varchar(20),数量 int,净重 float,毛重 float)
    insert into test select 'A4','T1','B001','2000',6.80,8.12
    insert into test select 'A4','T2','B002','4000',null,null
    insert into test select 'A5','T3','B003','5000',6.70,7.04
    insert into test select 'A6','T3','B004','4500',5.50,6.56
    go
    --测试select 物料类型,round(sum(净重),2)净重,round(sum(毛重),2) 毛重
    from(
    select b.物料类型,
    b.数量*a.净重/a.数量 as 净重,
    b.数量*a.毛重/a.数量 as 毛重
    from(
    select 箱号,sum(数量)数量,sum(净重)净重,sum(毛重)毛重 from test
    group by 箱号)a inner join test b
    on a.箱号=b.箱号)t
    group by 物料类型
    --删除测试环境
    drop table test
     set nocount off
    /*
    物料类型                 净重                     毛重
    -------------------- ---------------------- ----------------------
    T1                   2.27                   2.71
    T2                   4.53                   5.41
    T3                   12.2                   13.6
    */