MySQL:使用空行计算累积和

时间:2016-04-29 23:09:16

标签: mysql sql

当许多列具有空值时,如何计算列的累积总和?

我正在尝试以下操作,并且我的查询超时,没有特定的错误消息:

SELECT t1.time_purchased, 
    t1.savings AS daily_savings,
    SUM(t2.savings) AS total_savings
FROM items AS t1, 
    items AS t2
WHERE t1.time_purchased >= t2.time_purchased
GROUP BY t1.time_purchased;

time_purchased和储蓄行通常是空的 - 这会导致错误吗?如果是这样,我还可以做什么来跳过这些错误,同时仍然将节省的成本添加到total_savings?

理想情况下,我希望显示随时间累积的节省,与time_purchased无关。谢谢!

解决方案编辑:

感谢大家的帮助。最终的解决方案要求我的FROM语句从一个表中选择,其中存储没有空值,否则cumulative_sum继续为null,因为我在某些情况下添加了空值。请参阅以下解决方案:

SET @cumulative_sum := 0;
SELECT 
    time_purchased
    ,savings
    ,(@cumulative_sum := @cumulative_sum + savings) AS cumulative_sum
FROM (SELECT * FROM items WHERE savings IS NOT NULL) AS i
ORDER BY time_purchased;

1 个答案:

答案 0 :(得分:0)

在MySQL中,执行累积和的最简单方法是使用变量:

SELECT i.time_purchased,
       i.savings
       (@ds := @ds + i.savings) AS total_savings
FROM items i CROSS JOIN
     (SELECT @ds := 0) params 
ORDER BY i.time_purchased;

我不确定你想对NULL值做什么,但至少这不应该超时。