MSSQL Query从TABLE中删除重复的行,在表中留下不同的行

时间:2012-04-27 07:21:12

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

我需要从具有相同Logcustomer_id的表deactivation_date中删除除第一次出现之外的所有重复行。如何用最少的sql语句实现这一点。

我使用的是MS SQL Server 2008快速版。

3 个答案:

答案 0 :(得分:16)

类似的东西:

DELETE FROM Log WHERE LogId NOT IN 
 (SELECT Min(LogId) FROM Log GROUP BY customer_id, deactivation_date)

答案 1 :(得分:14)

或者:

with cte as (
    select row_number() over (partition by customer_id, deactivation_date
    order by log_id) as rn
    from Log)
delete from cte
    where rn > 1;

答案 2 :(得分:2)

你没有给我们太多的工作。但也许是这样的:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY [Log].customer_id ORDER BY 
                              deactivation_date) AS RowNbr,
        [Log].*
    FROM
        [Log]
)
DELETE FROM [Log]
WHERE EXISTS
    (
        SELECT
            NULL
        FROM
            CTE
        WHERE
            CTE.RowNbr>1
            AND CTE.log_id =[Log].log_id 
    )