在查询中丢弃某些相关行



我有一个宽的表,但是只有5列与问题有关。假设桌子是这样的:

BSNS_ID |VCH_ID |VCH_Line |PAY_STATUS |PAY_ID |银行|不com04 |00001 |1 |收到|000001 |BK01 |2970com04 |00001 |1 |等待|null |null |30com01 |00352 |1 |收到|000832 |BK98 |3000com01 |00352 |2 |收到|000967 |BK98 |6784com01 |00352 |2 |收到|000834 |BK98 |6784com33 |00023 |1 |收到|000076 |BK43 |4950com33 |00023 |1 |等待|null |null |50com02 |00065 |1 |等待|000804 |BK45 |9946

Bsns_IDVch_IDVch_Line是我的化合物键,可以识别特定项目,但是项目可以有多个付款,因此特定行的完整ID包括Pay_ID列。

我需要的是,以相同的Bsns_IDVch_IDVch_Line,将其相关行中的 Pay_Status = 'Pending'Pay_ID = NULL的任何行汇总,并丢弃所讨论的行。总和的结果必须替换相关行的Amnt值。样本结果就像:

BSNS_ID |VCH_ID |VCH_Line |PAY_STATUS |PAY_ID |银行|不com04 |00001 |1 |收到|000001 |BK01 |3000-(2970   30(com01 |00352 |1 |收到|000832 |BK98 |3000com01 |00352 |2 |收到|000967 |BK98 |6784com01 |00352 |2 |收到|000834 |BK98 |6784com33 |00023 |1 |收到|000076 |BK43 |5000-(4950   50(com02 |00065 |1 |等待|000804 |BK45 |9946

不存在以下行:

com04 |00001 |1 |等待|null |null |30com33 |00023 |1 |等待|null |null |50

编辑:我正在雪花上工作。

with pendings as (
    select Bsns_ID
        ,Vch_ID
        ,Vch_Line
        ,sum(Amnt) as s_Amnt
    from TABLE_NAME
    where pay_id is null
    group by 1,2,3
)
sekect a.Bsns_ID
    ,a.Vch_ID
    ,a.Vch_Line
    ,a.Pay_status
    ,a.Pay_ID
    ,a.Bank
    ,a.Amnt + coalesce(p.Amnt,0) as Amnt
from TABLE_NAME as a
left join pendings as p on a.bsns_id = p.bsns_id and a.vch_id = p.vch_id and a.Vch_Line = p.Vch_Line;

但是,就像@gordonlinoff所暗示的是,如果COM01 | 00352 | 2要具有第三行,它将与两行匹配。差距是您暗示pay_id应用作第四个唯一键 pay_id键添加到所有非磁性行中,这似乎很危险。

相关内容

  • 没有找到相关文章

最新更新