1

由于我的应用程序中的一个错误,为承载每个交付周期的每日记录而构建的表格被填充了很多次。

假设我从 6 月 1 日到 6 月 5 日有交货。我的表应该填充 5 条记录,每天一条。现在,我受到了严重破坏,因为我有许多相同内容的“批次”。

表格布局如下:

dummy_id       -- identity column
delivery_id    -- id of the delivery
on_date        -- the day
charge         -- the daily cost

有没有一种优雅的方法来只保留第一批记录并删除所有交付时错误插入的批次?

4

3 回答 3

2

删除所有重复项以delivery_id, on_date, charge保留最低的重复项dummy_id

;WITH cte
     AS (SELECT ROW_NUMBER() OVER (PARTITION BY delivery_id,
                                                on_date,
                                                charge
                                       ORDER BY dummy_id) RN
         FROM   YourTable)
DELETE FROM cte
WHERE  RN > 1
于 2012-11-02T16:04:04.183 回答
1

你可以试试:

这是为了知道您将删除哪些行:

SELECT * FROM YOUR_TABLE WHERE DUMMY_ID NOT IN (
   SELECT MIN(DUMMY_ID) FROM YOUR_TABLE GROUP BY DELIVERY_ID)

这将删除这些行:

DELETE FROM YOUR_TABLE WHERE DUMMY_ID NOT IN (
   SELECT MIN(DUMMY_ID) FROM YOUR_TABLE GROUP BY DELIVERY_ID)
于 2012-11-02T16:05:17.553 回答
1

尝试

DELETE FROM table WHERE dummy_id NOT IN (SELECT MIN(dummy_id) FROM table GROUP BY on_date)
于 2012-11-02T16:06:34.843 回答