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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pang_da_xing/article/details/78897933
-- 设置可唯一识别的字段(此处是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)

猜你喜欢

转载自blog.csdn.net/pang_da_xing/article/details/78897933
今日推荐