sql 数据去重并且保留一条(在一定的时间范围随机获取时间)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pang_da_xing/article/details/79617307
-- 将lmt作为唯一标识确保唯一

update SWS_ST_SPB_P set lmt = t.lmt
from 
SWS_ST_SPB_P s,
(
SELECT stcd, mpcd, tm, v1, v2, v3, r1, r2, r3,  
DATEADD(second, ABS(CHECKSUM(NEWID())) % DATEDIFF(second,'00:00','23:59'), CONVERT(char(20),tm,20) ) as lmt
from SWS_ST_SPB_P s
) t
where s.stcd = t.stcd and s.mpcd = t.mpcd and s.tm = t.tm 

-- 重复数据只保留一条

DELETE from SWS_ST_SPB_P where 
stcd in (SELECT stcd from SWS_ST_SPB_P GROUP BY stcd, mpcd, tm HAVING count(*)>1)
and tm  in (SELECT tm from SWS_ST_SPB_P GROUP BY stcd, mpcd, tm HAVING count(*)>1)
and mpcd  in (SELECT mpcd from SWS_ST_SPB_P GROUP BY stcd, mpcd, tm HAVING count(*)>1)
and lmt not in (SELECT max(lmt) from SWS_ST_SPB_P GROUP BY stcd, mpcd, tm HAVING count(*)>1)

猜你喜欢

转载自blog.csdn.net/pang_da_xing/article/details/79617307