删除重复批次的数据

时间:2012-11-02 15:57:15

标签: sql sql-server sql-server-2008

由于我的应用程序中存在一个错误,因此每个交付周期的日常记录都会生成一个表格。

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

表格布局如下:

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

是否有一种优雅的方法可以只保留第一批记录并删除错误插入的批次以进行所有交付?

3 个答案:

答案 0 :(得分:2)

删除delivery_id, on_date, charge的所有dupes,保持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

答案 1 :(得分: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)

答案 2 :(得分:1)

尝试

DELETE FROM table WHERE dummy_id NOT IN (SELECT MIN(dummy_id) FROM table GROUP BY on_date)