对两个表中的重复行值求和

时间:2017-08-28 15:38:36

标签: sql group-by sum

我试图从一行中的两个表中获取以下信息,但是当我使用group by时,我总是得到两行:

Doc Headers

Section Doc     Year    Nr
SEC1    PATAG   2017    7386

Doc Lines

Section Doc     Year    Nr      Line Type   Quantity
SEC1    PATAG   2017    7386    0           1.000000
SEC1    PATAG   2017    7386    4           2.000000

查询

SELECT
cab.strCodSeccao as [Section], cab.strAbrevTpDoc as [Doc], cab.strCodExercicio 
as [Year], cab.intNumero as [Nr], 
Cast (SUM (lin.fltQuantidade) as NUMERIC (15,2) ) as [Quantity],
CASE WHEN lin.intTpEntPagador = 0 THEN Cast (SUM (lin.fltQuantidade) as 
NUMERIC (15,2) ) ELSE 0 END as [Qtd Client],
CASE WHEN lin.intTpEntPagador = 4 THEN Cast (SUM (lin.fltQuantidade) as 
NUMERIC (15,2) ) ELSE 0 END as [Qtd Warranty]

FROM    
Mov_Apv_Reparacao_Lin as lin WITH (NOLOCK)
LEFT OUTER JOIN Mov_Apv_Reparacao_Cab as cab ON 
(lin.strCodseccao=cab.strCodSeccao AND Cab.strAbrevTpDoc=Lin.strAbrevTpDoc AND 
Cab.strCodExercicio=Lin.strCodExercicio AND Cab.intNumero=Lin.intNumero)

WHERE   
cab.strAbrevTpDoc='PATAG' AND cab.strcodexercicio = 
2017 and cab.intnumero = 7386

GROUP BY 
cab.strCodSeccao, cab.strAbrevTpDoc, cab.strCodExercicio, cab.intNumero, 
lin.intTpEntPagador

查询结果

Section Doc     Year    Nr      Quantity    Qtd Client  Qtd Warranty
SEC1    PATAG   2017    7386    1.00        1.00        0.00
SEC1    PATAG   2017    7386    2.00        0.00        2.00

期望的结果

Section Doc     Year    Nr      Quantity    Qtd Client  Qtd Warranty
SEC1    PATAG   2017    7386    3.00        1.00        2.00

提前致谢。

2 个答案:

答案 0 :(得分:1)

group by中的属性过多:您应该删除lin.intTpEntPagador。这也意味着你必须改变你的案例/总结:

Cast(SUM(CASE WHEN lin.intTpEntPagador = 0 THEN lin.fltQuantidade ELSE 0 END) as 
NUMERIC (15,2) ) as [Qtd Client]

您还应删除distinct,如果您还group by

,则该功能无效

答案 1 :(得分:1)

尝试将SUM()移到CASE之外:

SELECT cab.strCodSeccao as [Section], 
       cab.strAbrevTpDoc as [Doc], 
       cab.strCodExercicio as [Year], 
       cab.intNumero as [Nr], 
       CAST(SUM(lin.fltQuantidade) as NUMERIC (15,2)) as [Quantity],
       CAST(SUM(CASE WHEN lin.intTpEntPagador = 0 
            THEN lin.fltQuantidade
            ELSE 0 
       END) AS NUMERIC (15,2)) as [Qtd Client],
       CAST(SUM(CASE WHEN lin.intTpEntPagador = 4 
            THEN lin.fltQuantidade
            ELSE 0 
       END) AS NUMERIC (15,2)) as [Qtd Warranty]

附注,当您已经拥有DISTINCT

时,此处无需GROUP BY