SQL - 标记行直到每组的 0 值

SQL - Flag rows till 0 value of each group

我正在计算一个 运行 余额,并希望将所有行标记为 0 值以具有 'MATCHED' 标记 else 'NOT-MATCHED' 关于帐户 ID 的标记。

这是我尝试过但没有得到正确结果的方法:

SEL a.*, 
CASE WHEN RUNNING_BALANCE OVER (PARTITION BY ACCT_SROGT_ID ROWS UNBOUNDED PRECEDING ) = 0 THEN 'M' ELSE 'NM' END R 
FROM NON_MATCHING_RUNNING_BALANCE  a

我们可以使用 sub-query 找到最后一个 acct_rank 是 0,然后用 case 来测试每一行。

Select
  a.*,
  Case when a.acct_rank > z.last_zero
    Then 'unmatched' else 'matched' 
    End as is_matched
From accounts a
Join ( select 
         account_id as id,
         MAX(acct_rank) last_zero
       From accounts
       Where running_balance = 0
       Group by account_id) z
On a.account_id = z.id;

勾选这个

WITH SUB AS  (
select NON_MATCHING_RUNNING_BALANCE.*,row_number()over(partition by [Account ID] order by [Account ID]) RN from NON_MATCHING_RUNNING_BALANCE
)
SELECT SUB.*,CASE WHEN SUB.RN<=SUB2.RN AND SUB.[Account ID]=SUB2.[Account ID] THEN 'MATCHED' ELSE 'Not-Matched' END AS 'MATCH' FROM SUB LEFT JOIN (
SELECT * FROM SUB WHERE value=0 ) SUB2 ON SUB.[Account ID]=SUB2.[Account ID]