[英]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. 换句话说,SUM()没有返回正确的值。 I know my subquery is correctly returning the values I'm looking for but when I GROUP and SUM the values become very incorrect.
我知道我的子查询正确返回了我要查找的值,但是当我进行GROUP和SUM时,这些值变得非常不正确。 I'm dealing with positive and negative amounts but my understanding is SUM() should still work correctly.
我正在处理正数和负数,但是我的理解是SUM()应该仍然可以正常工作。 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. 在您的内部SQL中,有一个“按期间划分的GROUP”,但您不是按“期间+帐户”进行汇总,而仅按“期间”进行汇总。 Please try removinge the acccount in the GROUP BY
请尝试删除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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.