用于删除重复记录的SQL脚本

时间:2016-07-21 11:08:02

标签: sql-server

需要SQL脚本来删除重复记录。以下是示例数据 •示例1:运行脚本之前

CreatedWhen               Status    CVGUID      LocGUID 
-----------------------  ---------------- --------------- -------------
2015-11-04 11:00:00.667    CUR    65400270        5300610      
2015-11-04 10:44:36.327    PRV    65400270        5300610      
2015-11-04 10:43:03.340    INA    65400270        5300610      
2015-11-04 10:39:34.100    INA    65400270        5300610      
2015-11-04 10:35:17.880    INA    65400270        5300610      

•示例1:运行脚本后

CreatedWhen              Status ClientVisitGUID LocationGUID  
----------------------- ---------------- --------------- -------------
2015-11-04 11:00:00.667   CUR    65400270        5300610      

•示例2:运行脚本之前

CreatedWhen              Status CVGUID          LocGUID 
 -----------------------  ------ ---------------- -------------
 2015-11-09 04:41:16.340  CUR    65500270         6000610      
 2015-11-09 04:40:00.527  PRV    65500270         6000610      
 2015-11-09 04:38:13.790  INA    65500270         5300610      
 2015-11-09 04:33:23.843  INA    65500270         5300610      

•示例2:运行脚本后

CreatedWhen              Status CVGUID          LocGUID 
 -----------------------  ------ ---------------- -------------
2015-11-09 04:41:16.340  CUR    65500270         6000610            
 2015-11-09 04:33:23.843 PRV    65500270         5300610    

•示例3:运行脚本之前

CreatedWhen              Status CVGUID          LocGUID 
 -----------------------  ------ ---------------- -------------
2015-11-09 06:07:19.880  CUR    65600270         6000610      
 2015-11-09 06:06:48.970  PRV    65600270         5300610      
 2015-11-09 06:06:24.890  INA    65600270         7100610      
 2015-11-09 06:06:00.330  INA    65600270         6000610      
 2015-11-09 06:03:52.070  INA    65600270         5300610    

•示例3:运行脚本后(不应有任何更改)

CreatedWhen              Status CVGUID          LocGUID  
 -----------------------  ------ ---------------- -------------
 2015-11-09 06:07:19.880  CUR    65600270         6000610      
 2015-11-09 06:06:48.970  PRV    65600270         5300610      
 2015-11-09 06:06:24.890  INA    65600270         7100610      
 2015-11-09 06:06:00.330  INA    65600270         6000610      
 2015-11-09 06:03:52.070  INA    65600270         5300610     

2 个答案:

答案 0 :(得分:0)

  1. 使用空格作为分隔符将数据拆分为列
  2. 使用ROW_NUMBER()OVER(由CVGUID分区,由CreatedWhen创建的LOCGUID ORDER)来标记重复项
  3. 使用row_number>删除所有行1
  4. 如果您不知道如何执行上述步骤,我建议您使用Google或堆栈溢出来查找答案,因为这些是非常常见的问题

答案 1 :(得分:0)

试试这个:

With cte as
(
  SELECT MAX(CreatedWhen) CreatedWhen, CVGUID, LocGUID
  INTO #temp
  FROM TableName
  GROUP BY CVGUID, LocGUID
)
With cte2 as
(
  SELECT CreatedWhen, ROW_NUMBER() OVER (ORDER BY CreatedWhen DESC PARTITION BY CVGUID) row_num, CVGUID, LocGUID
  FROM cte 
)
SELECT CreatedWhen, CASE WHEN row_num = 1 THEN 'CUR' WHEN row_num = 2 THEN 'PRV' ELSE 'INA' END Status, CVGUID, LocGUID
FROM cte2;

如果解决方案有任何问题,请告诉我。