我想删除重复的行,但条件如下
name | tier |
—————————————|
geeni | 1 |
geeni | 1 |
geeni | 2 |
geeni | 3 |
geeni | 4 |
geeni | 4 |
geeni | 5 |
如何从 3 及以下的最小值中删除重复的行,但保留上面的其余行(4 和 5),即使它们也重复?
name | tier |
—————————————|
geeni | 4 |
geeni | 4 |
geeni | 5 |
保留 4 的重复项而不删除它(仅 3,2 和 1)。如果可能的话请告诉我!到T
-- Step 1: Identify the rows to keep (tiers 4 and 5).
WITH RowsToKeep AS (
SELECT
name,
tier
FROM
YourTableName
WHERE
tier >= 4
),
-- Step 2: Identify the rows to delete based on conditions.
RowsToDelete AS (
SELECT
name,
tier,
ROW_NUMBER() OVER (PARTITION BY name, tier ORDER BY (SELECT NULL)) AS rn
FROM
YourTableName
WHERE
tier < 4
AND EXISTS (
SELECT 1
FROM RowsToKeep
WHERE RowsToKeep.name = YourTableName.name
AND RowsToKeep.tier = YourTableName.tier
)
)
-- Step 3: Delete the identified rows.
DELETE FROM YourTableName
WHERE EXISTS (
SELECT 1
FROM RowsToDelete
WHERE RowsToDelete.name = YourTableName.name
AND RowsToDelete.tier = YourTableName.tier
AND RowsToDelete.rn > 1 -- Keeping one instance of each duplicate.
);