TSQL 2008 R2
我有重复的订单项,每个订单项都有自己的给定PO#的唯一ID。我需要删除重复项。我不知道每个PO#有多少重复。因为有一个#LineItems我知道我只想要第一个(顶部)x(#lineIems)行项目。
我有一张这样的表:
LineitemID PO# #LineItems
---------- ------- ----------
11111111 12345 3
22222222 12345 3
33333333 12345 3
44444444 12345 3
55555555 12345 3
66666666 12345 3
77777777 54321 2
88888888 54321 2
99999999 54321 2
10101010 54321 2
...
我需要一张这样的表:
LineitemID PO# #LineItems
---------- ------- ----------
11111111 12345 3
22222222 12345 3
33333333 12345 3
77777777 54321 2
88888888 54321 2
...
所以基本上有办法做这样的事情:
DECLARE @top int = (SELECT TOP 1 FROM tblLineItems t WHERE t.PO# = @PO)
SELECT TOP (@top)
FROM tblLineItems
按照每个PO#
执行此操作答案 0 :(得分:2)
delete t from (select *, rank = row_number() over (partition by PO# order by lineitemid)
from table ) t
where rank > #lineitems
答案 1 :(得分:2)
在facepalm之后删除了第一个答案。
您的示例唯一的问题是您在TOP查询中没有ORDER BY,这可能会以任何顺序拉出结果。此查询假定您按LineItemID(整数类型)ASC进行排序。
DECLARE @LineItems TABLE
(
LineItemID INT
, PO INT
, NumLineItems INT
)
INSERT INTO @LineItems (LineItemID, PO, NumLineItems)
SELECT 11111111, 12345, 3
UNION ALL SELECT 22222222, 12345, 3
UNION ALL SELECT 33333333, 12345, 3
UNION ALL SELECT 44444444, 12345, 3
UNION ALL SELECT 55555555, 12345, 3
UNION ALL SELECT 66666666, 12345, 3
UNION ALL SELECT 77777777, 54321, 2
UNION ALL SELECT 88888888, 54321, 2
UNION ALL SELECT 99999999, 54321, 2
UNION ALL SELECT 10101010, 54321, 2
DELETE b
FROM
(
SELECT *
, RANK() OVER (PARTITION BY PO, NumLineItems ORDER BY LineItemID ASC) AS r
FROM @LineItems
) a
JOIN @LineItems b
ON a.LineItemID = b.LineItemID
WHERE r > a.NumLineItems
SELECT *
FROM @LineItems
ORDER BY PO, LineItemID