Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 删除重复记录,只保留最新记录_Sql_Sql Server - Fatal编程技术网

Sql 删除重复记录,只保留最新记录

Sql 删除重复记录,只保留最新记录,sql,sql-server,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

我在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
我需要做以下工作:

根据给定国家/地区ID的问题\ ID,从表中将重复记录复制到answersArchive表中,并将其从答案中删除 我意识到,因此我需要两个查询。目前,我只想查询具有MaxUpdate值的最新答案,但查询结果不正确:

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;
任何暗示都将不胜感激

使用行数分析函数

 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内部或外部使用Count filter

您可以使用Count with partition by查找重复记录并将其插入到answersArchive表中,如下所示

1-查找副本并插入应答器配置单元表

2-删除除最新副本外的所有副本

您可以使用CTE删除记录。要查找重复记录,可以使用行号和按问题划分的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 
;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