sql - 使用 oracle sql 在 where 子句中计算带有日期范围的运行总计
问题描述
我有一张表,我想在 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')
谢谢,
解决方案
您想要的输出(第 1 - 7 行中的样本数据;查询从第 8 行开始)。
SQL> with test (transaction_id, transaction_date, quantity) as
2 (select 1, date '2020-05-03', 3 from dual union all
3 select 2, date '2020-05-06', 5 from dual union all
4 select 3, date '2020-06-05', 10 from dual union all
5 select 4, date '2020-07-06', 2 from dual union all
6 select 5, date '2020-08-07', 8 from dual
7 )
8 select transaction_id,
9 transaction_date,
10 quantity,
11 sum(quantity) over (order by transaction_date) running_total
12 From test
13 where transaction_date between date '2020-05-03' and date '2020-07-06'
14 order by transaction_id;
TRANSACTION_ID TRANSACTIO QUANTITY RUNNING_TOTAL
-------------- ---------- ---------- -------------
1 03.05.2020 3 3
2 06.05.2020 5 8
3 05.06.2020 10 18
4 06.07.2020 2 20
SQL>
你的问题的原因?我认为这是您将日期与字符串进行比较的事实('03-May-20'
是字符串,而不是日期)。Oracle 尝试隐式转换数据类型;有时会成功,有时不会。例如,您03-May-20
可能是 2020 年 5 月 3 日或 2003 年 5 月 20 日。
始终控制您的数据。必要时使用日期,或者使用to_date
带有适当日期格式掩码的函数,或者使用日期文字(就像我一样)。
推荐阅读
- java - 如何实现多个属性的绑定以相互监听?
- c# - 如何从具有列表的元素列表中返回列表
- c++ - C ++:登录错误,识别大于0的有效三角形,提供所有三个角度
- c++ - txChart Arduino 的问题
- java - Java 递归打印金字塔星形图案
- javascript - 如何从对象返回特定键
- powerbi - 基于日期列将 Power BI 中的单行转换为多行
- serialization - toml crate 如何构建类似依赖的结构
- python - Python 错误:元组索引必须是整数或切片,而不是 str
- r - Group_by_at 和 summarise_ 在使用闪亮/降价可再现时产生值。R