sql - 按组 SQL 运行总计 (Oracle)

标签 sql oracle cumulative-sum

我在 Oracle 数据库中有一个表,其中包含以下感兴趣的字段:位置、产品、日期、金额。我想编写一个查询,按位置、产品和日期获取总金额。我在下面放了一个示例表,说明我想要的结果。

我可以得到一个运行总数,但是当我到达一个新的位置/产品时我无法重置它。这是我迄今为止的代码,任何帮助将不胜感激,我觉得这是一个简单的修复。

select a.*, sum(Amount) over (order by Location, Product, Date) as Running_Amt
from Example_Table a

+----------+---------+-----------+------------+------------+
| Location | Product | Date      | Amount     |Running_Amt |
+----------+---------+-----------+------------+------------+
| A        | aa      | 1/1/2013  | 100        | 100        |
| A        | aa      | 1/5/2013  | -50        | 50         |
| A        | aa      | 5/1/2013  | 100        | 150        |
| A        | aa      | 8/1/2013  | 100        | 250        |
| A        | bb      | 1/1/2013  | 500        | 500        |
| A        | bb      | 1/5/2013  | -100       | 400        |
| A        | bb      | 5/1/2013  | -100       | 300        |
| A        | bb      | 8/1/2013  | 250        | 550        |
| C        | aa      | 3/1/2013  | 550        | 550        |
| C        | aa      | 5/5/2013  | -50        | 600        |
| C        | dd      | 10/3/2013 | 999        | 999        |
| C        | dd      | 12/2/2013 | 1          | 1000       |
+----------+---------+-----------+------------+------------+

最佳答案

啊,我想我已经想通了。

select a.*, sum(Amount) over (partition by Location, Product order by Date) as Running_Amt
from Example_Table a

关于sql - 按组 SQL 运行总计 (Oracle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155401/

相关文章:

sql - 如何将每行 SUM() 转换为另一列

asp.net - 将用户配置文件 SQL 数据库导入到 Windows Azure

php - MySQL SELECT 查询中的捆绑记录,存储为时间戳

sql - Spark SQL语句广播

Django - Oracle 后端错误

java - 用于在 Java 中保存连接字符串参数的配置文件

SQL COUNT 条记录在表 2 JOINS 掉

sql - 为什么我收到 ORA-01401 : inserted value too large for column - when I'm not inserting?

postgresql - Postgres 随着时间的推移累积计数

r - 为每个用户创建具有多个条件的累积计数器变量