Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I select a column to sum total price from earlier date

Tags:

sql

mysql

+--------+---------+-------+--------+
| billID | orderId | price |  date  |
+--------+---------+-------+--------+
|      1 |       1 |   100 | 1.3.12 |
|      2 |       1 |   230 | 1.4.12 |
|      3 |       1 |   300 | 1.5.12 |
|      4 |       2 |  1000 | 1.3.12 |
|      5 |       2 |   160 | 1.4.12 |
|      6 |       3 |   400 | 1.3.12 |
+--------+---------+-------+--------+

I want to create view that have column that sum all price have same orderID but with date earlier than rows date. Like this:

+--------+---------+-------+--------+--------------+
| billID | orderId | price |  date  | add-on price |
+--------+---------+-------+--------+--------------+
|        |         |       |        |              |
|      1 |       1 |   100 | 1.3.12 |          100 |
|      2 |       1 |   230 | 1.4.12 |          330 |
|      3 |       1 |   300 | 1.5.12 |          630 |
|      4 |       2 |  1000 | 1.3.12 |         1000 |
|      5 |       2 |   160 | 1.4.12 |         1160 |
|      6 |       3 |   400 | 1.3.12 |          400 |
+--------+---------+-------+--------+--------------+
like image 399
gianglaodai Avatar asked Oct 31 '22 13:10

gianglaodai


1 Answers

You can user a correlated subquery for this:

select t.*,
       (select sum(t2.price)
        from table t2
        where t2.orderId = t.orderId and t2.date <= t.date
       ) as CumulativePrice
from table t;
like image 119
Gordon Linoff Avatar answered Nov 09 '22 21:11

Gordon Linoff