[英]MySQL cumulative sum order by date
我正在按日期执行累积总和订单,但没有得到预期的结果。 与总和使用的顺序相比,某些记录的显示顺序不同。
我期望以下结果之一:
或以下顺序:
(添加)请注意,负值也是可能的。 这就是为什么我在下面的答案中提到累积金额的顺序不能解决问题的原因。 例如,我将略微修改结果:
谢谢您的帮助。
http://sqlfiddle.com/#!9/7204d4/2提供了您所期望的输出。.我在查询后添加了@cum:= @cum + tot_earn_pts-tot_redeem_pts asc。
按“ cum_liability_pts” desc的顺序添加其他字段:
SELECT *
FROM (
SELECT date,
tot_earn_pts,
tot_redeem_pts,
tot_earn_pts - tot_redeem_pts AS tot_liability_pts,
@cum := @cum + tot_earn_pts - tot_redeem_pts AS cum_liability_pts
FROM (
SELECT date,
earn_points AS tot_earn_pts,
redeem_points AS tot_redeem_pts
FROM i_report_total_order
/* WHERE website_id = 36 */
) tots
JOIN (SELECT @cum := 0) init
ORDER BY date asc
) res_asc
ORDER BY date desc, cum_liability_pts desc;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.