sql - 创建查询以添加减少总数

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

我有以下两张表。

表1

身份证 金额
1 5000
2 3000
3 4000

表2

PO_ID PO 顺序 PO_金额
1 PO1 1 2000
2 PO2 2 4000

我想以这样的方式连接这两个表,使表 2 中的 PO 金额将在表 1 金额列中使用。例如。如下所示。 PO_Alloc_Amount 和 PO_Remaining_Amount 将被计算列

身份证 金额 PO PO_金额 PO_Alloc_Amount PO_剩余_金额
1 5000 PO1 2000 2000 0
1 5000 PO2 4000 3000 1000
2 3000 PO2 4000 1000 0
3 4000

例如。在表 1 中,ID 1 的金额为 5000。因此,为了根据该金额进行调整,将从 PO1 中取出 2000,从 PO2 中取出 3000(来自表 2)。这些金额将显示在 PO_Alloc_Amount 列中。

此后,PO2 将有 1000 金额,将用于表 1 中的 ID 2。 ID 3 将显示空值,因为没有 PO 值可用于它。

如果您需要更多信息,请告诉我。

我期待输出查询来解决我的问题

sql
1个回答
0
投票
with t1 as (
    select *,
        sum(Amount) over (order by Id) as totalAmount
    from Table1
), t2 as (
    select *,
        sum(PO_Amount) over (order by Id) as totalPO_Amount
    from Table2
)
from t1 left outer join Tables t2
    on t1.totalAmount - t1.Amount >= t2.totalPO_Amount
   and t1.totalAmount < t2.totalPO_Amount - t2.PO_Amount;
© www.soinside.com 2019 - 2024. All rights reserved.