为什么MySQL中的这个累加和不起作用?

时间:2018-08-17 08:30:24

标签: mysql

我想获取两个日期之间每小时的累计订单总和:

SELECT tDate, nHour, COUNT(tIPN) AS num, (@csum := @csum + COUNT(tIPN)) as sum

FROM TBL_DATES
JOIN TBL_HOURS 
LEFT JOIN VIEW_PAYPAL ON DATE(tIPN) = tDate AND HOUR(tIPN) = nHour
JOIN (SELECT @csum := 0) r

WHERE tDate BETWEEN '2018-08-05' AND '2018-08-17'

GROUP BY tDate, nHour

ORDER BY tDate, nHour;

但是我得到这个结果:

tDate       nHour num sum
2018-08-05  0     2   2
2018-08-05  1     1   1
2018-08-05  2     0   0
2018-08-05  3     0   0
2018-08-05  4     0   0
2018-08-05  5     0   0
2018-08-05  6     2   2
2018-08-05  7     4   4
2018-08-05  8     5   5
2018-08-05  9     5   5
2018-08-05  10    5   5
2018-08-05  11    7   7
2018-08-05  12    11  11

我在做什么错?我尝试使用单独的SET语句,但没有区别。

1 个答案:

答案 0 :(得分:0)

此代码应为您工作:

SET @csum := 0;

SELECT tDate, nHour, COUNT(tIPN) AS num, (@csum := @csum + COUNT(tIPN)) as cumulative_sum

FROM TBL_DATES
JOIN TBL_HOURS 
LEFT JOIN VIEW_PAYPAL ON DATE(tIPN) = tDate AND HOUR(tIPN) = nHour

WHERE tDate BETWEEN '2018-08-05' AND '2018-08-17'

GROUP BY tDate, nHour

ORDER BY tDate, nHour;

首先,应使用@csum初始化SET变量。

第二,最好使用名为sum的列别名,因为这是一个保留关键字。