Hi @elsvieta
Try this query:
CREATE TABLE #Demo (ID INT,Line INT,Amount INT)
INSERT INTO #Demo VALUES
(100 ,1, 1000),
(100, 2, 100),
(100 ,1, 100),
(100 ,2, 1000),
(101 ,1 ,2000),
(101 ,2 ,500),
(101 ,3, 50),
(101 ,1, 50),
(101 ,2, 2000),
(101 ,3, 500)
;WITH CTE AS
(
SELECT *,ROW_NUMBER()OVER(PARTITION BY ID,Line ORDER BY Amount DESC) AS DESC_Order
,ROW_NUMBER()OVER(PARTITION BY ID,Line ORDER BY Amount ASC) AS ASC_Order
FROM #Demo
)
DELETE
FROM CTE
WHERE (Line = 1 AND DESC_Order <> 1) OR (Line <> 1 AND ASC_Order <> 1)
SELECT * FROM #Demo
Best regards,
Cosmog
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".