价格表:
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查询?
答案 0 :(得分:1)
select date,
@total := @total + price as running_total,
price
from your_table, (select @total := 0) r
order by date
答案 1 :(得分:1)
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
答案 2 :(得分:0)
使用几乎标准的SQL;
SELECT *, (SELECT SUM(price)
FROM pricetable p
WHERE p.date<=pricetable.date) total
FROM pricetable
ORDER BY date;
......或LEFT JOIN ......
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;