简体   繁体   中英

SQL - Sum and Group By returning incorrect sums

So I have the query below which I believe should be working correctly but is returning false values

SELECT 
    Period,
    Sum(Amount) as amount

FROM (
    SELECT
        Period,
        Sum(Amount) Amount
    FROM (
        SELECT a.Period, a.Account, SUM(a.Amount) amount
        FROM LedgerAP a
        WHERE a.Period >= @custPeriodStart AND a.Period <= @custPeriodEnd
        GROUP BY a.Period, a.Account

        UNION
        SELECT b.Period, b.Account, SUM(b.Amount) amount
        FROM LedgerAR b
        WHERE b.Period >= @custPeriodStart AND b.Period <= @custPeriodEnd
        GROUP BY b.Period, b.Account

        UNION
        SELECT c.Period, c.Account, SUM(c.Amount) amount
        FROM LedgerEx c
        WHERE c.Period >= @custPeriodStart AND c.Period <= @custPeriodEnd
        GROUP BY c.Period, c.Account

        UNION
        SELECT d.Period, d.Account, SUM(d.Amount) amount
        FROM LedgerMisc d
        WHERE d.Period >= @custPeriodStart AND d.Period <= @custPeriodEnd
        GROUP BY d.Period, d.Account
    ) src1
    GROUP BY Period, Account
) src2

Group by Period

What I'm getting is:

Period  |  Amount
201501  |  -450.00
201502  |  00
201503  |  00
...     |  ...
201512  |  xxxxxx

What I'm expecting is:

Period  |  Amount
201501  |  1731262
201502  |  774221
201503  |  770845
...     |  ...
201512  |  xxxxxx

In other words SUM() isn't returning the correct values. I know my subquery is correctly returning the values I'm looking for but when I GROUP and SUM the values become very incorrect. I'm dealing with positive and negative amounts but my understanding is SUM() should still work correctly. Any ideas?

in your inner SQL there is a GROUP by Period, Account althoug you are not summing up by period + account but only by period. Please try removinge the acccount in the GROUP BY

SELECT
    Period,
    Sum(amount1) Amount
FROM (
    SELECT a.Period, a.Account, SUM(a.Amount) amount1
    FROM LedgerAP a
    WHERE a.Period >= @custPeriodStart AND a.Period <= @custPeriodEnd
    GROUP BY a.Period, a.Account

    UNION
    SELECT b.Period, b.Account, SUM(b.Amount) amount1
    FROM LedgerAR b
    WHERE b.Period >= @custPeriodStart AND b.Period <= @custPeriodEnd
    GROUP BY b.Period, b.Account

    UNION
    SELECT c.Period, c.Account, SUM(c.Amount) amount1
    FROM LedgerEx c
    WHERE c.Period >= @custPeriodStart AND c.Period <= @custPeriodEnd
    GROUP BY c.Period, c.Account

    UNION
    SELECT d.Period, d.Account, SUM(d.Amount) amount1
    FROM LedgerMisc d
    WHERE d.Period >= @custPeriodStart AND d.Period <= @custPeriodEnd
    GROUP BY d.Period, d.Account
) src1
GROUP BY Period

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM