从同一个表中删除重复行的 SQL 代码

问题描述

我有下表,其中包含为相同 test_id 复制的数据。 cas_rn 14808-79-8 和 18785-72-3 是同一种物质。我需要删除 14808-79-8 的所有实例,其中同一 test_id 存在一行,但 cas_rn 为 18785-72-3。

test_id cas_rn 计数 result_numeric
260058 14808-79-8 1 4.0000000000
260058 18785-72-3 1 4.0000000000
260062 14808-79-8 1 6.7000000000
260062 18785-72-3 1 6.7000000000
260067 14808-79-8 1 79.0000000000
260067 18785-72-3 1 79.0000000000
260072 14808-79-8 1 710.0000000000
260072 18785-72-3 1 710.0000000000
260077 14808-79-8 1 150.0000000000
260077 18785-72-3 1 150.0000000000

查询显示行,但我需要添加 DELETE 语句:

SELECT 
    test_id,[cas_rn],COUNT(test_id) 'Count',result_numeric
  FROM [dbo].[dt_result]

  WHERE cas_rn IN ('14808-79-8','18785-72-3') AND facility_id = '247561'

  GROUP BY test_id,cas_rn,result_numeric

解决方法

如果您的查询返回所需的结果,删除非常简单:

DELETE  [dbo].[dt_result] 
WHERE test_id IN (SELECT test_id 
                  FROM dbo.dt_result
                  WHERE cas_rn IN ('18785-72-3') AND facility_id = '247561')