我有下表(test_table):
date value
---------------
d1 10.0
d1 20.0
d2 60.0
d2 10.0
d2 -20.0
d3 40.0
我计算运行总数如下。我两次使用相同的查询,因为首先我需要计算特定日期的值,然后我可以计算运行总计。否则,加入两个日期不是唯一的表,每个日期都会得到太多结果:
SELECT t1.date, SUM(t2.value) AS total
FROM
(SELECT date, SUM(value) AS value FROM test_table GROUP BY date) AS t1
JOIN
(SELECT date, SUM(value) AS value FROM test_table GROUP BY date) AS t2
ON t1.date >= t2.date
GROUP BY t1.date
ORDER BY t1.date
这给了我(很好):
date total
-------------
d1 30.0
d2 80.0
d3 120.0
但是,这个查询效率不高,因为如果需要,我需要在两个地方更改条件。在生产中,test_table 要大得多(> 4 Mio. rows),并且查询需要太多时间才能完成。问题:如何避免两次使用相同的查询?