Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Removing the last child record from same parent if seque
Message
 
 
À
26/06/2015 10:29:18
Information générale
Forum:
Microsoft SQL Server
Catégorie:
Syntaxe SQL
Versions des environnements
SQL Server:
SQL Server 2012
Application:
Web
Divers
Thread ID:
01621484
Message ID:
01621485
Vues:
76
This message has been marked as the solution to the initial question of the thread.
>I have a data fix to apply based on child records, where two detail records have sometimes been added in sequence. When this is the case, I need to remove the most recent one.
>
>So, basically, I have a Client table. Then, I have an Invoice table. This is the typical example scenario. This does not represent the real tables and fields I am using.
>
>For each client, I need to get the Invoice records. If the last two records of the Invoice table have the same status, for example Completed, I need to remove the most recent one.
>
>What would be the easier approach to resolve that?
;with cteRows as (select *, row_number() over (partition by ClientID order by AddedDate DESC) as RowNumber 
from Invoices)

delete from cteRows R where RowNumber = 1  and Status = 'Completed' 
and exists (select * from cteRows where RowNumber = 2 and Status = 'Completed' 
and R.ClientId = cteRows.ClientId)
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform