将 DELETE FROM 与 LEAD 函数一起使用
Using DELETE FROM with LEAD function
使用 SQL Server 2014,我有一个 table 可以跟踪收银机的销售情况。如果注册操作员错误地扫描了一个项目,它将创建两条记录 - 一条 SALE
条记录和一条 VOID
条记录。
TRX_ID LINE_ID STS ITEM_DESC
-----------------------------------------------------
123456 1 Sale Sunglasses Mens RS124
123456 2 Void Sunglasses Mens RS124
123456 3 Sale Sunglasses NXR RS977
123456 4 Void Sunglasses NXR RS977
123456 5 Sale Sunglasses Unisex RS355
123678 1 Sale Sunglasses Womens RS124w
123678 2 Void Sunglasses Womens RS124w
123678 3 Sale Sunglasses Womens RS977w
123678 4 Sale Sunglasses Womens RS977w
123678 5 Sale Sunglasses Unisex RS355w
如果交易中的以下项目已作废 (STS='VOID'),我需要编写一个查询来删除记录,只保留 'net' 个交易。
我正在使用 LEAD
让查询检查以下记录,我只是不知道如何将 DELETE FROM
和 LEAD
组合在一起。我尝试使用此查询未成功:
DELETE FROM SALES
WHERE xxx IN (SELECT
TRX_ID, LINE_ID, LEAD (T1.STS, 1, 0) OVER (PARTITION BY T1.TRX_ID ORDER BY T1.LINE_ID) NEXT_STS
FROM SALES_TRANSACTIONS T1)
WHERE NEXT_STS = 'V'
例外结果:以下记录被删除:
TRX_ID LINE_ID STS ITEM_DESC
----------------------------------------------------
123456 1 Sale Sunglasses Mens RS124
123456 2 Void Sunglasses Mens RS124
123456 3 Sale Sunglasses NXR RS977
123456 4 Void Sunglasses NXR RS977
123678 1 Sale Sunglasses Womens RS124w
123678 2 Void Sunglasses Womens RS124w
您可以通过多种方式做到这一点。一种是在常见的 table 表达式中使用 lead
,然后从中删除:
with extra as (
select sts,
lead(sts) over (partition by trx_id order by line_id) leadsts
from sales
)
delete
from extra
where 'Void' in (sts, leadsts);
使用 SQL Server 2014,我有一个 table 可以跟踪收银机的销售情况。如果注册操作员错误地扫描了一个项目,它将创建两条记录 - 一条 SALE
条记录和一条 VOID
条记录。
TRX_ID LINE_ID STS ITEM_DESC
-----------------------------------------------------
123456 1 Sale Sunglasses Mens RS124
123456 2 Void Sunglasses Mens RS124
123456 3 Sale Sunglasses NXR RS977
123456 4 Void Sunglasses NXR RS977
123456 5 Sale Sunglasses Unisex RS355
123678 1 Sale Sunglasses Womens RS124w
123678 2 Void Sunglasses Womens RS124w
123678 3 Sale Sunglasses Womens RS977w
123678 4 Sale Sunglasses Womens RS977w
123678 5 Sale Sunglasses Unisex RS355w
如果交易中的以下项目已作废 (STS='VOID'),我需要编写一个查询来删除记录,只保留 'net' 个交易。
我正在使用 LEAD
让查询检查以下记录,我只是不知道如何将 DELETE FROM
和 LEAD
组合在一起。我尝试使用此查询未成功:
DELETE FROM SALES
WHERE xxx IN (SELECT
TRX_ID, LINE_ID, LEAD (T1.STS, 1, 0) OVER (PARTITION BY T1.TRX_ID ORDER BY T1.LINE_ID) NEXT_STS
FROM SALES_TRANSACTIONS T1)
WHERE NEXT_STS = 'V'
例外结果:以下记录被删除:
TRX_ID LINE_ID STS ITEM_DESC
----------------------------------------------------
123456 1 Sale Sunglasses Mens RS124
123456 2 Void Sunglasses Mens RS124
123456 3 Sale Sunglasses NXR RS977
123456 4 Void Sunglasses NXR RS977
123678 1 Sale Sunglasses Womens RS124w
123678 2 Void Sunglasses Womens RS124w
您可以通过多种方式做到这一点。一种是在常见的 table 表达式中使用 lead
,然后从中删除:
with extra as (
select sts,
lead(sts) over (partition by trx_id order by line_id) leadsts
from sales
)
delete
from extra
where 'Void' in (sts, leadsts);