如何选择一列来汇总早期日期的总价格

时间:2014-11-28 14:26:59

标签: mysql sql

+--------+---------+-------+--------+
| 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 |
+--------+---------+-------+--------+

我想创建一个视图,其中包含总和所有价格的列具有相同的orderID但日期早于行日期。像这样:

+--------+---------+-------+--------+--------------+
| 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 |
+--------+---------+-------+--------+--------------+

1 个答案:

答案 0 :(得分:2)

您可以为此使用相关的子查询:

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