删除重复的记录,仅保留最新的记录

时间:2019-03-19 07:48:38

标签: sql sql-server

我在MSSQL中有一个名为answers的表,它看起来像:

ID Answer Country_ID Question_ID Updated
1  ans1    15          20        2018-10-14 13:17:02.680
2  ans2    15          20        2018-11-19 13:17:02.680
3  ans0    15          20        2018-11-20 13:17:02.680
4  ans5    15          22        2018-10-14 13:17:02.680

我需要执行以下操作:

  • 从表中复制,将根据Question_ID将给定国家/地区ID的重复记录回答到answersArchive表中,并将其从answers中删除

我意识到,为此,我需要两个查询。目前,我只想查询最近的答案(具有max(Updated)值),但是查询结果不正确:

select *
from answers a
inner join (
    select Question_ID, max(Updated) as MaxDate
    from answers
    WHERE Country_ID = 15
    group by Question_ID
) a2 on a.Question_ID = a2.Question_ID and a.Updated = a2.MaxDate
where a.Country_ID = 15
order by a.Question_ID;

任何提示都值得赞赏。

2 个答案:

答案 0 :(得分:2)

使用row_number()分析函数

 with cte as
(
 select t.*,row_number()over(partition by Question_ID order by Updated desc) rn
 from answers t
 where country_id=15
) delete from cte where rn<>1

---您可以在cte内部或外部使用国家/地区过滤器

答案 1 :(得分:2)

您可以将Countpartition by一起使用,以查找重复的记录并将其插入到answersArchive表中,如下所示。

1-查找重复项并插入 answersArchive

--copy the duplicate records
;WITH cte 
     AS (SELECT id, 
                answer, 
                country_id, 
                question_id, 
                updated, 
                Count(*) 
                  OVER( 
                    partition BY question_id ) ct 
         FROM   answers 
         WHERE  country_id = 15) 
INSERT INTO answersarchive 
SELECT id, 
       answer, 
       country_id, 
       question_id, 
       updated 
FROM   cte 
WHERE  ct > 1 --Give you duplicate records 

2-删除除最新重复项之外的所有重复项。

您可以使用CTE删除记录。要查找重复的记录,您可以将ROW_NUMBER()PARTITION BY question_id一起使用,例如以下查询。

;WITH cte 
     AS (SELECT id, 
                answer, 
                country_id, 
                question_id, 
                updated, 
                Row_number() 
                  OVER( 
                    partition BY question_id 
                    ORDER BY updated DESC) RN 
         FROM   answers 
         WHERE  country_id = 15) 

DELETE FROM cte 
WHERE  rn > 1 
相关问题