我有以下查询
SELECT date, t1.col1, t2.col2, t1.col1 * t2.col2 AS `col3`
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC
现在我想要添加一个累积总和为col3
的列,所以按照这个问题(Create a Cumulative Sum Column in MySQL)我想出了这个:
SET @csum := 0;
SELECT date, t1.col1, t2.col2, t1.col1 * t2.col2 AS `col3`, (@csum := @csum + `col3`) AS `sum`
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC
但由于col3
也是在查询中生成的,因此它显然无法正常工作。如何更改它以使生成的列可以有累积总和?
答案 0 :(得分:2)
您可以在col3
- 表达式中使用与@csum
相同的公式,也可以使用周围的select语句添加sum
- 列。
所以要么......
SET @csum := 0;
SELECT date, t1.col1, t2.col2, t1.col1 * t2.col2 AS `col3`, (@csum := @csum + (t1.col1 * t2.col2)) AS `sum`
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC
或......
SET @csum := 0;
SELECT ti.*, (@csum := @csum + ti.col3) AS `sum`
FROM (
SELECT date, t1.col1, t2.col2, t1.col1 * t2.col2 AS `col3`,
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC) ti
答案 1 :(得分:0)
SET @csum := 0;
SELECT
date, t1.col1, t2.col2,
@tmp := t1.col1 * t2.col2 AS `col3`,
@csum := @csum + @tmp AS `sum`
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC
OR
SELECT
date, t1.col1, t2.col2,
@tmp := t1.col1 * t2.col2 AS `col3`,
@csum := IFNULL(@csum, 0) + @tmp AS `sum`
FROM t1
INNER JOIN t2 ON t2.col3 = t1.col3
WHERE t2.col3 = 2
ORDER BY date ASC
答案 2 :(得分:0)
虽然@StephanLechners在直接使用MySQL数据库(使用phpmyadmin等工具)时可以解答,但在我的情况下,在将我的查询添加到我的PHP代码时,它无效。所以万一有人遇到类似的问题,这里的查询对我有用。
我正在使用WordPress,所以使用$wpdb->get_results
来执行查询。这可能是Stephans查询对我不起作用的原因之一。
所以有效的查询如下。
SELECT t.date, t.col1, t.col2, t.sum, @runtot:=@runtot + t.sum AS cumulativesum
FROM (SELECT date, t1.col1, t2.col2, t2.col2 * col1 AS `sum`
FROM t1
INNER JOIN t2 ON t1.col3 = t2.col3
WHERE t2.id = 2) t
JOIN (SELECT @runtot := 0 AS dummy) dummy
ORDER BY date