来自先前选择结果的Sum表列

时间:2014-04-23 11:28:01

标签: sql-server sum

我有3张桌子

ITEMS(LOCNUMBER, CODE)
LOCATIONS(LOCNUMBER)
PLANT(CODE, UNITS)

我根据位置编号选择所有结果(见下文)

    select DISTINCT l.LOCNUMBER, i.CODE 
    from Locations l 
    inner join ITEMDETAILS i 
      on l.LOCNUMBER = i.LOCNUMBER 
    where l.LOCNUMBER= '4577';

这给了我以下内容,但我现在需要根据查询返回的每个CODE查询PLANT表和SUM(UNITS)?怎么办呢?

    LOCNUMBER   CODE
    4577        C44A
    4577        GE-AOR
    4577        GE-ARH
    4577        GE-ARP
    4577        GE-ARV
    4577        GE-BP
    4577        GE-EC
    4577        GE-EES
    4577        GE-JB
    4577        GE-JT
    4577        GE-JTR
    4577        GE-VL2
    4577        GE-VL4
    4577        L01A

1 个答案:

答案 0 :(得分:1)

select l.LOCNUMBER, i.CODE,SUM(Units) 
    from Locations l 
    inner join ITEMDETAILS i 
      on l.LOCNUMBER = i.LOCNUMBER 
    inner join plant p
      on p.code=i.code
    where l.LOCNUMBER= '4577'
    GROUP BY  l.LOCNUMBER, i.CODE