SQL将两个联合的总和数量合计为一行

时间:2016-03-25 21:51:50

标签: sql-server sql-server-2008 tsql

如何将使用union all的两个查询中的金额汇总到一列和一行?现在它分为两行,但我只希望TotalQty列的差异在一行中。

    select sum(begsdquantity)as 'TotalQty', CUSIPNumber, ForeignCountry
from 
    (
        select sum (abs(b.begsdquantity)) begsdquantity, B.CUSIPNumber, C.FOREIGNCOUNTRY 
        from USBI.vw_NameAddressBase a
        inner join USBI.vw_StockRecord b on a.FirmAccountId = b.FirmAccountId
        inner join USBI.vw_SecurityBase c on b.FirmCUSIPId = c.FirmCUSIPId
        WHERE '20160229' between a.EffectiveDate and a.ExpirationDate
        AND '20160229' between b.EffectiveDate and b.ExpirationDate
        and '20160229' between c.EffectiveDate and c.ExpirationDate
        AND c.ForeignCountry NOT IN ('US', 'VA', 'RQ', 'VQ')
        and b.CUSIPNumber = '654902204'
        and b.AcctType in ('0') 
        and b.LocMemo = 's'
        GROUP BY B.CUSIPNumber, C.ForeignCountry        

        union ALL

        select sum(-b.begsdquantity) begsdquantity, B.CUSIPNumber, C.ForeignCountry 
        from USBI.vw_NameAddressBase a
        INNER join USBI.vw_StockRecord b on a.FirmAccountId = b.FirmAccountId
        inner join USBI.vw_SecurityBase c on b.FirmCUSIPId = c.FirmCUSIPId
        where a.RestrDate in ('99999999')
        AND a.CloseRestrictInd in ('C')
        AND c.ForeignCountry NOT IN ('US', 'VA', 'RQ', 'VQ')
        and '20160229' between a.EffectiveDate and a.ExpirationDate
        and '20160229' between b.EffectiveDate and b.ExpirationDate
        and '20160229' between c.EffectiveDate and c.ExpirationDate
        and b.CUSIPNumber = '654902204'
        GROUP BY B.CUSIPNumber, C.ForeignCountry

    ) t

group by begsdquantity, CUSIPNumber, ForeignCountry

ORDER BY CUSIPNumber

我的结果:

enter image description here

我正在寻找一列和一行中TotalQty列96061的差异。这是可能的还是我做错了什么?

1 个答案:

答案 0 :(得分:3)

制作最后一行......

int.filter(function(a){ return a%2==0});

即通过

取出小组中的begsdquantity