我需要从具有相同Log
和customer_id
的表deactivation_date
中删除除第一次出现之外的所有重复行。如何用最少的sql语句实现这一点。
我使用的是MS SQL Server 2008快速版。
答案 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
)