我按日期执行累计金额订单,但我没有得到预期的结果。与用于总和的订单相比,某些记录以不同的顺序显示。
Please have a look at SQL Fiddle
我希望得到以下结果:
2015-05-05T00:00:00Z 50 30 20 90 120
2015-05-05T00:00:00Z 60 30 30 120 100
2015-05-04T00:00:00Z 70 50 20 30 70
2015-05-04T00:00:00Z 80 40 40 70 50
2015-05-03T00:00:00Z 30 20 10 10
或以下顺序:
2015-05-05T00:00:00Z 60 30 30 120
2015-05-05T00:00:00Z 50 30 20 90
2015-05-05T00:00:00Z 60 30 30 120
2015-05-04T00:00:00Z 80 40 40 70
2015-05-04T00:00:00Z 70 50 20 30
2015-05-04T00:00:00Z 80 40 40 70
2015-05-03T00:00:00Z 30 20 10 10
(已添加)请注意,负值也是可能的。这就是为什么我在下面的答案中提到累积金额的顺序不能解决问题的原因。作为一个例子,我将略微修改结果:
2015-05-05T00:00:00Z 30 60 -30 60
2015-05-05T00:00:00Z 50 30 20 90
2015-05-04T00:00:00Z 80 40 40 70
2015-05-04T00:00:00Z 70 50 20 30
2015-05-03T00:00:00Z 30 20 10 10
感谢您的帮助。
答案 0 :(得分:0)
http://sqlfiddle.com/#!9/7204d4/2 给出你的expceted输出..我在你的查询后添加了@cum:= @cum + tot_earn_pts --tot_redeem_pts asc。
答案 1 :(得分:0)
按“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;