How can I select a column to calculate the total price from an earlier date

+--------+---------+-------+--------+ | 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 a view that has a column that sums the entire price, has the same orderID, but with a date earlier than the row 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 | +--------+---------+-------+--------+--------------+ 
+5
source share
1 answer

For this you can correlated subquery:

 select t.*, (select sum(t2.price) from table t2 where t2.orderId = t.orderId and t2.date <= t.date ) as CumulativePrice from table t; 
+2
source

Source: https://habr.com/ru/post/1207891/


All Articles