我创建了一个查询
DELETE
FROM [dbo].[AKA$Item Stock Changes Log] AS gone,SELECT t.[Item No_] ,
t.[Last Date Modified] ,
t.[Location Code]
FROM (
SELECT [Item No_] ,
[Last Date Modified] ,
[Location Code] ,
[Activity]
FROM [dbo].[AKA$Item Stock Changes Log]) AS t
WHERE t.[Last Date Modified]<
(
SELECT Max(b.[Last Date Modified])
FROM (
SELECT [Item No_] ,
[Last Date Modified] ,
[Location Code] ,
[Activity]
FROM [dbo].[AKA$Item Stock Changes Log]) AS b
WHERE b.[Location Code]=t.[Location Code]
AND b.[Item No_]=t.[Item No_]) as needed
WHERE gone.[Item No_]=needed.[Item No_]
AND gone.[Location Code]=needed.[Location Code]
AND gone.[Last Date Modified]=needed.[Last Date Modified]
名为needed
的子查询包含我要删除的行。但查询不起作用,我不知道如何处理。
以下是一些示例数据。
我的主要目标是查询获取[Item No_]
和[Location Code]
相等的行并删除除最新
Item No_ Last Date Modified Location Code
-------------------- ----------------------- --------------------
0015672 2017-12-28 14:28:51.847 JV should stay
0015672 2017-12-28 14:28:51.847 KN should stay
0015672 2017-12-28 14:28:48.990 JV delete
0015672 2017-12-28 14:28:48.990 KN delete
0015672 2017-12-28 14:28:30.547 JV delete
0015672 2017-12-28 14:28:30.547 KN delete
0036539 2017-12-28 14:27:54.190 KN
0036539 2017-12-28 14:27:54.190 JV
0044623 2017-12-28 14:27:54.190 KN
0044623 2017-12-28 14:27:54.190 JV
0036539 2017-12-28 14:27:48.850 KN
0036539 2017-12-28 14:27:48.850 JV
答案 0 :(得分:3)
您可以CTE
使用ROW_NUMBER()
。这将从源表中删除记录。
;with cte as (
select
*
,RN = row_number() over (partition by [Item No_], [Location Code] order by [Last Date Modified] desc)
from
YourTable)
delete from cte where RN <> 1