SQL Server SUM,但由另一列聚合

时间:2014-10-15 20:16:31

标签: sql sql-server sum

我正在使用以下SQL查询来汇总项目中的所有付款类型:

SELECT 
    SUM(E2_SALDO) as SUM,
    E2_ITEMD as PROJECT,
    E2_ZFORPG AS TYPE 
FROM 
    SE2010 
WHERE 
    D_E_L_E_T_ = ''
    AND E2_NUM BETWEEN '' AND 'ZZZZZZZZZZZZZZZ' 
    AND E2_PREFIXO BETWEEN '' AND 'ZZZ' 
    AND E2_NATUREZ BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_VENCREA BETWEEN '20140901' AND '20140915'
    AND E2_PORTADO BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_FORNECE BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_EMISSAO BETWEEN '20000101' AND '20201231'
    AND E2_ZFORPG BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_ZTPED BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_SALDO> 0  and E2_TIPO<>'PR' AND E2_ITEMD BETWEEN '' AND 'ZZZZZZZZZZZZZ' 
GROUP BY 
    E2_ITEMD, E2_ZFORPG

我的结果看起来像这样

SUM         PROJECT    TYPE
-----------------------------
848,15      F140319               
7296,36     H1008       DOC          
14534,02    H1008       TED          
36041,33    K0104       BOL       
11127,91    F140363     CAM       
84841,43    H1008       CAM       
500                     CHQ       
1600        K0309       CHQ       
4124,91                 DEB       
200         F130702     DOC       
3394,64     H1001       DOC       
7674,54     H1001       TED     

几乎就是这样,但我想“结合”一些结果,例如我希望以“H”开头的项目的所有成本合在一起,如下所示:

SUM         PROJECT      TYPE
------------------------------
10691       H1001,H1008   DOC       
22208,56    H1001,H1008   TED       
84841,43    H1008         CAM       

因此,在此示例中,它为“H”项目(第1行)中的所有内容分组了所有DOC付款类型,将所有“TED”付款类型(第2行)分组,并且还有单独显示项目时没有其他项目(第3行,因为在任何地方都没有“H1001 CAM”)

如果可能的话,我想手动通知某个地方的群组类型,因为有时候我想把“H”和“K”项目放在一起,所以我想通知一个()中的“群组”,就像在a“WHERE TYPE IN(”first“,”second“)

谢谢!

编辑:运行Microsoft SQL Server 2008 R2

1 个答案:

答案 0 :(得分:0)

SELECT
    SUM(E2_SALDO) AS sum,
    E2_ITEMD =
    STUFF((
        SELECT
            ', ' + E2_ITEMD
        FROM
            SE2010 b
        WHERE
            b.E2_ITEMD = a.E2_ITEMD 
            AND b.E2_ITEMD LIKE '['+@yourProjectNameStartCharacters + ']%'-- H if only starting with H, HK if you want starting with h and k
        FOR xml PATH ('')), 1, 2, ''),
    E2_ZFORPG 
FROM
    SE2010
WHERE
    D_E_L_E_T_ = ''
    AND E2_NUM BETWEEN '' AND 'ZZZZZZZZZZZZZZZ'
    AND E2_PREFIXO BETWEEN '' AND 'ZZZ'
    AND E2_NATUREZ BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_VENCREA BETWEEN '20140901' AND '20140915'
    AND E2_PORTADO BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_FORNECE BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_EMISSAO BETWEEN '20000101' AND '20201231'
    AND E2_ZFORPG BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_ZTPED BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_SALDO > 0
    AND E2_TIPO <> 'PR'
    AND E2_ITEMD BETWEEN '' AND 'ZZZZZZZZZZZZZ'
    AND E2_ITEMD LIKE '['+@yourProjectNameStartCharacters + ']%'-- H if only starting with H, HK if you want starting with h and k
GROUP BY
    E2_ZFORPG