Eliminar filas de ID no únicas
-
03-07-2019 - |
Pregunta
Desde una copia de seguridad de la base de datos tengo registros sin identificadores únicos.
Algunos registros tienen identificadores únicos. Algunos registros con ID duplicados contienen diferentes valores DateCreated. Algunos registros con ID duplicados contienen los mismos valores DateCreated.
Estoy intentando obtener una consulta de MSSql 2005 solo dejará valores de ID únicos con el valor DateCreated más reciente.
Desde
ID| DateCreated
1 | 1/1/09
2 | 1/2/09
2 | 2/2/09
3 | 1/3/09
3 | 1/3/09
A
ID| DateCreated
1 | 1/1/09
2 | 2/2/09
3 | 1/3/09
Ayuda
Solución
DELETE FROM myTable AS t1
WHERE EXISTS (
SELECT 1 FROM myTable AS t2
WHERE t1.ID=t2.ID AND t1.DateCreated<t2.DateCreated)
es decir, elimine cualquier fila donde haya otra fila con el mismo ID y una fecha de creación posterior.
Otros consejos
create table #t ( id int, date datetime )
insert #t
values(1, getdate())
insert #t
values(1, getdate()+1)
insert #t
values(1, getdate()-1)
insert #t
values(2, getdate())
insert #t
values(2, getdate()+1)
delete t
from #t t
left join (select id, min(date) as date from #t group by id) as t1
on t.id = t1.id and t1.date = t.date
where t1.date is null
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow