什么是SQL语句在某个activity发生后删除一个ID的所有条目?

What is the SQL Statement to delete all entries of an ID after a certain activity occurs?

我正在努力使用 Vertica SQL 语句在特定事件发生后删除 OrderID 的所有条目。

这是我的数据的表示。

**OrderID     Activity**  
1             Item Started  
1             Task 1 complete  
1             In storage  
1             Deletion   
1             Deletion Complete  
2             Item Started  
2             Deletion  
2             Deletion Complete  

在这种情况下,我想删除 OrderID 1 的条目 "Deletion" 和 "Deletion Complete",因为它们出现在 activity "In storage" 之后。我想保留 OrderID 1 的所有条目直到(包括)"In Storage"。

OrderID 2 不是这种情况,因此我想保留它。

您可以分两步删除第 1 步删除所有 'In storage' 不可用的记录

 DELETE FROM table t1 WHERE 
 not exists ( select 1 from table t2 where t1.id=t2.id
                                 and Activity in ('In storage')
 )

第二步 'In storage' 可用

DELETE FROM table t1 where activity in('Deletion','Deletion Complete')

如果您的情况与您描述的完全一样——并且您确实没有相关的时间戳,以检查之前发生的事情和之后发生的事情——那么您可以删除所有 activity 为 [=15] 的行=] 或 'Deletion Complete' 并且其 orderid 等于 activity 为 'In storage' 的任何行的任何订单 ID。

但是,如果 'In storage' 需要在 'Deletion' 或 'Deletion Complete' 之前发生,那么您还需要在我下面使用的子选择中验证这一点。

-- create the example table - drop any table of that name existing before ...
DROP TABLE IF EXISTS input;
CREATE TABLE input(OrderID,Activity) AS (
          SELECT 1,'Item Started'
UNION ALL SELECT 1,'Task 1 complete'
UNION ALL SELECT 1,'In storage'
UNION ALL SELECT 1,'Deletion'
UNION ALL SELECT 1,'Deletion Complete'
UNION ALL SELECT 2,'Item Started'
UNION ALL SELECT 2,'Deletion'
UNION ALL SELECT 2,'Deletion Complete'
);
-- here goes 
DELETE
FROM  input
WHERE orderid IN (
  SELECT orderid FROM input WHERE activity='In storage'
)
  AND activity IN('Deletion','Deletion Complete')
;