SQL - Sum和Group返回错误的总和

时间:2015-12-10 20:30:15

标签: sql sql-server group-by sum

所以我有下面的查询,我认为应该正常工作,但返回错误的值

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

我得到的是:

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

我期待的是:

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

换句话说,SUM()没有返回正确的值。我知道我的子查询正确地返回我正在寻找的值但是当我GROUP和SUM时,值变得非常不正确。我正在处理积极和消极的金额,但我的理解是SUM()仍应正常工作。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在你的内部SQL中有一个GROUP by Period,Account虽然你没有按期间+帐户汇总,但只是按期间汇总。请尝试删除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