价目表:
date | price
------------------
2014-01-01 100
2014-01-02 20
2014-01-03 -30
2014-01-04 70
...是否可以使用SQL查询显示结果表?
成果表:
date | price | total
--------------------------
2014-01-01 100 100
2014-01-02 20 120
2014-01-03 -30 90
2014-01-04 70 160
...是否可以编写此SQL查询?
发布于 2014-04-19 16:22:41
select date,
price,
@total := @total + price as total
from (select date, price
from your_table
order by date) x
CROSS JOIN (select @total := 0) r发布于 2014-04-19 16:21:30
select date,
@total := @total + price as running_total,
price
from your_table, (select @total := 0) r
order by date发布于 2014-04-19 16:24:04
使用相当标准的SQL;
SELECT *, (SELECT SUM(price)
FROM pricetable p
WHERE p.date<=pricetable.date) total
FROM pricetable
ORDER BY date;一个要测试的SQLfiddle。
...or向左转.
SELECT *, SUM(p2.price) total
FROM pricetable p1
LEFT JOIN pricetable p2
ON p1.date >= p2.date
GROUP BY p1.date, p1.price
ORDER BY p1.date;另一个SQLfiddle。
https://stackoverflow.com/questions/23172423
复制相似问题