SQL SUM - ambigous导致多连接查询

时间:2016-11-24 12:00:58

标签: sql sql-server join sum

我有这条SQL:

SELECT 
    PO.[Replan Ref_ No_], 
    PO.[Source No_], 
    ISNULL(SUM(PZ.[Cantitate sudura]), 0) As Sudate, 
    ISNULL(SUM(PZ.[Cantitate montaj]),0) as Montate, 
    ISNULL(SUM(CONVERT(INT, CC.[Cantitate Validata])), 0) as QtyValidata
FROM
    [SC Vermorel SRL$Production Order] AS PO 
LEFT OUTER JOIN 
    [SC Vermorel SRL$ProductieZilnica] AS PZ ON PZ.FPO = PO.[Replan Ref_ No_]
LEFT OUTER JOIN 
    [SC Vermorel SRL$PregatirePROD] AS PP ON PP.FPO = PO.[Replan Ref_ No_]
LEFT OUTER JOIN 
    [SC Vermorel SRL$CalitateCTC] as CC ON CC.NrFpo = PO.[Replan Ref_ No_] 
                                        AND CC.[Cod Articol] = PO.[Source No_]
WHERE 
    PO.[Location Code] = 'MACH FIN' 
    AND (PO.Status = 3)
GROUP BY 
    PO.[Replan Ref_ No_], PO.[Source No_]

返回以下结果:

enter image description here

我在屏幕上方突出显示了特定SUM的{​​{1}} Cantitate ValidataQtyValidata的结果。奇怪的是总和无意义的总和。在Bellow中,您会找到一个带有查询的屏幕以及Replan Ref No_完成表格的结果,指出SUM Replan Ref No_应该是1. {12}。有人能弄清楚发生了什么吗?

enter image description here

2 个答案:

答案 0 :(得分:1)

也许这个问题适合你。


SELECT 
    PO.[Replan Ref_ No_], 
    PO.[Source No_], 
    ISNULL(PZA.Sudate, 0) As Sudate, 
    ISNULL(Montate,0) as Montate, 
    ISNULL(CCA.QtyValidata), 0) as QtyValidata
FROM
    [SC Vermorel SRL$Production Order] AS PO 
OUTER APPLY (
    SELECT 
        SUM(PZ.[Cantitate sudura]) As Sudate,
        SUM(PZ.[Cantitate montaj]) as Montate,
    FROM [SC Vermorel SRL$ProductieZilnica] AS PZ 
    WHERE PZ.FPO = PO.[Replan Ref_ No_]
    GROUP BY PZ.FPO  -- maybe this group by not need for you
) PZA
OUTER APPLY (
    SELECT
        SUM(CONVERT(INT, CC.[Cantitate Validata])) as QtyValidata
    FROM [SC Vermorel SRL$CalitateCTC] as CC
    WHERE CC.NrFpo = PO.[Replan Ref_ No_] 
        AND CC.[Cod Articol] = PO.[Source No_]
    GROUP BY CC.NrFpo, CC.[Cod Articol] -- maybe this group by not need for you
) CCA
WHERE 
    PO.[Location Code] = 'MACH FIN' 
    AND PO.Status = 3
GROUP BY 
    PO.[Replan Ref_ No_], PO.[Source No_]

答案 1 :(得分:0)

你在某种程度上重复加入的行......

要识别有问题的联接,请运行不带group by的查询,如此...

SELECT 
    PO.[Replan Ref_ No_], 
    PO.[Source No_], 
    PZ.[Cantitate sudura] As Sudate, 
    PZ.[Cantitate montaj] as Montate, 
    CONVERT(INT, CC.[Cantitate Validata]) as QtyValidata
FROM
    [SC Vermorel SRL$Production Order] AS PO 
LEFT OUTER JOIN 
    [SC Vermorel SRL$ProductieZilnica] AS PZ ON PZ.FPO = PO.[Replan Ref_ No_]
LEFT OUTER JOIN 
    [SC Vermorel SRL$PregatirePROD] AS PP ON PP.FPO = PO.[Replan Ref_ No_]
LEFT OUTER JOIN 
    [SC Vermorel SRL$CalitateCTC] as CC ON CC.NrFpo = PO.[Replan Ref_ No_] 
                                    AND CC.[Cod Articol] = PO.[Source No_]
WHERE 
    PO.[Location Code] = 'MACH FIN' 
    AND (PO.Status = 3)