SQL 视图(或查询)显示一段时间内的累积总和

问题描述 投票:0回答:1

假设我在名为

transactions
的 SQL 表中有以下数据,主键为
tx_date
location
item
:

tx_date       location    item         quantity    fee
2024-01-01    US          ITEM.123         1000     20
2024-02-04    EMEA        ITEM.456789       600     12
2024-03-09    US          ITEM.123         -750    -30
2024-04-12    EMEA        ITEM.456789       700     25
2024-05-16    EMEA        ITEM.456789      -800    -35

如何创建一个视图来显示每个

net_quantity
上每个
net_fee
对的
(location, item)
tx_date
?实际上,随着时间的推移累积总和:

tx_date       location    item        net_quantity   net_fee
2024-01-01    US          ITEM.123            1000        20
2024-02-04    EMEA        ITEM.456789          600        12
2024-03-09    US          ITEM.123             250       -10
2024-04-12    EMEA        ITEM.456789         1300        37
2024-05-16    EMEA        ITEM.456789          500         2
sql group-by sql-view
1个回答
0
投票
WITH CumulativeSums AS (
SELECT
    tx_date,
    location,
    item,
    quantity,
    fee,
    SUM(quantity) OVER (PARTITION BY location, item ORDER BY tx_date) AS net_quantity,
    SUM(fee) OVER (PARTITION BY location, item ORDER BY tx_date) AS net_fee
FROM
    transactions

) 选择 交易日期, 地点, 物品, 净数量, 净费用 从 累计金额 订购依据 地点, 物品, 交易日期; 在此输入图片描述

© www.soinside.com 2019 - 2024. All rights reserved.