Rimuovi le righe degli ID non univoci
-
03-07-2019 - |
Domanda
Da un backup del database ho record senza ID univoci.
Alcuni record hanno ID univoci. Alcuni record con ID duplicati contengono valori DateCreated diversi. Alcuni record con ID duplicati contengono gli stessi valori DateCreated.
Sto cercando di ottenere una query MSSql 2005 lascerà solo valori ID univoci con il valore DateCreated più recente.
Da
ID| DateCreated
1 | 1/1/09
2 | 1/2/09
2 | 2/2/09
3 | 1/3/09
3 | 1/3/09
Per
ID| DateCreated
1 | 1/1/09
2 | 2/2/09
3 | 1/3/09
Aiuto
Soluzione
DELETE FROM myTable AS t1
WHERE EXISTS (
SELECT 1 FROM myTable AS t2
WHERE t1.ID=t2.ID AND t1.DateCreated<t2.DateCreated)
ovvero, eliminare qualsiasi riga in cui è presente un'altra riga con lo stesso ID e una data di creazione successiva.
Altri suggerimenti
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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow