如果标签为“错误”,我需要删除所有PaymentId 实例。
CREATE TABLE Test (Id INT, PaymentId INT, Label VARCHAR(25)); INSERT INTO Test VALUES (1, 22, 'Error'), (2, 22, 'Seattle'), (3, 22, 'Pending'), (4, 33, 'Paid'), (5, 33, 'Los Angeles'), (6, 44, 'Houston'), (7, 44, 'Error'), (8, 55, 'Pending'), (9, 55, 'San Diego'), (10, 55, 'Authorization') SELECT * FROM Test
预期输出:
通过 CTE 和窗口函数的另一种选择sum() over()
sum() over()
;with cte as ( SELECT * ,Flg = sum( case when Label='Error' then 1 end) over (partition by PaymentID) FROM Test ) Delete from cte where Flg >=1
更新的表格