1. 程式人生 > >sql 資料去重並且保留一條(在一定的時間範圍隨機獲取時間)

sql 資料去重並且保留一條(在一定的時間範圍隨機獲取時間)

-- 將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)