从SQL Math操作获取不正确的值?

时间:2014-11-13 17:36:34

标签: mysql

我正在执行一项操作,根据2个值计算出一个百分比。

我有一张表来跟踪数月和年的整体价值。

表名 - donation_tracker

enter image description here

我正在比较当前和上一年的所有月份,然后进行计算,例如:

当前值(月 - 1月,2014年,CityID-1)/上一个值(月 - 1月,2013年,CityID-1)=除法值* 100 =新百分比值。

某些数学运算似乎是正确的,但有些是不正确的,例如下面的图像显示为140时应为130.

enter image description here

我要查询的价值如下: enter image description here

列donation_amount设置为

Type = Decimal

长度= 10,2。

总和应该是130 ......

SQL CODE -

SELECT city_markers.City_ID, city_markers.City_Name, city_markers.City_Lng, city_markers.City_Lat, SUM( d2.Donation_Amount ) , d1.Month, d1.Year, round( (
D2.Donation_amount / D1.Donation_amount
) *100, 2 )
FROM `city_markers`
INNER JOIN donation_tracker d1 ON city_markers.City_ID = d1.City_ID
INNER JOIN donation_tracker D2 ON d1.month = D2.month
AND d1.month = 'January'
AND d2.month = 'January'
AND d2.year = '2014'
AND D1.year = D2.year -1
AND D1.Location_ID = D2.Location_ID
GROUP BY city_markers.City_ID

谢谢。

1 个答案:

答案 0 :(得分:1)

您不会在此汇总金额:

round( (D2.Donation_amount / D1.Donation_amount) *100, 2 )

因此结果由每个第一行的值计算:

round( (70 / 50) *100, 2 ) ==> 140

使用sum()获得预期结果:

round( (sum(D2.Donation_amount) / sum(D1.Donation_amount)) *100, 2 )