【发布时间】:2020-10-25 20:38:32
【问题描述】:
我有一张表,我想用 where 子句中的日期范围计算运行总计
+----------------+------------------+----------+
| Transaction ID | Transaction Date | Quantity |
+----------------+------------------+----------+
| 1 | 03-May-20 | 3 |
| 2 | 06-May-20 | 5 |
| 3 | 05-Jun-20 | 10 |
| 4 | 06-Jul-20 | 2 |
| 5 | 07-Aug-20 | 8 |
+----------------+------------------+----------+
现在我的 oracle sql 查询是
select
transaction_id,
transaction_date,
sum(quantity) over (order by transaction_date) as running_total
from table
where transaction_date >= '03-May-20' and transaction_date <= '06-Jul-20'
运行上面的查询后,我得到了下面的结果
+----------------+------------------+----------+---------------+
| Transaction ID | Transaction Date | Quantity | Running Total |
+----------------+------------------+----------+---------------+
| 1 | 03-May-20 | 3 | 28 |
| 2 | 06-May-20 | 5 | 33 |
| 3 | 05-Jun-20 | 10 | 43 |
| 4 | 06-Jul-20 | 2 | 45 |
+----------------+------------------+----------+---------------+
这是错误的,因为我想要的输出是:
| Transaction ID | Transaction Date | Quantity | Running Total |
+----------------+------------------+----------+---------------+
| 1 | 03-May-20 | 3 | 3 |
| 2 | 06-May-20 | 5 | 8 |
| 3 | 05-Jun-20 | 10 | 18 |
| 4 | 06-Jul-20 | 2 | 20 |
+----------------+------------------+----------+---------------+
请帮助我应该使用什么查询来计算 where 子句中的日期范围的运行总计。
您好,我尝试使用 to_date 函数,但得到的结果与上面相同(第 2 个表)。请参阅下面的查询,
select
transaction_id,
transaction_date,
sum(quantity) over (order by transaction_date) as running_total
from table
where transaction_date between TO_DATE('2019-03-01', 'YYYY-MM-DD') AND TO_DATE('2020-10-25', 'YYYY-MM-DD')
谢谢,
【问题讨论】:
-
我看不出您的数据如何生成您指定的数据。数量之和大于您在表格中显示的数量。