SQL SERVER 将数据库中重复数据删除且只保留一条

时间:2022-09-22 22:41:56
-- 设置可唯一识别的字段(此处是lmt)
update update_t_datameas set lmt = t.lmt
from
update_t_datameas s,
(
SELECT stcd, POINTID, dt, v1, v2, v3, r1, r2, r3,
DATEADD(second, ABS(CHECKSUM(NEWID())) % DATEDIFF(second,'00:00','23:59'), CONVERT(char(20),dt,20) ) as lmt
from update_t_datameas s
) t
where s.stcd = t.stcd and s.POINTID = t.POINTID and s.dt = t.dt

-- 设置保留lmt时间最大的一条数据
DELETE from update_t_datameas where
stcd in (SELECT stcd from update_t_datameas GROUP BY stcd, POINTID, dt HAVING count(*)>1)
and dt in (SELECT dt from update_t_datameas GROUP BY stcd, POINTID, dt HAVING count(*)>1)
and POINTID in (SELECT POINTID from update_t_datameas GROUP BY stcd, POINTID, dt HAVING count(*)>1)
and lmt not in (SELECT max(lmt) from update_t_datameas GROUP BY stcd, POINTID, dt HAVING count(*)>1)