Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Removing the last child record from same parent if seque
Message
 
 
To
26/06/2015 10:29:18
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Environment versions
SQL Server:
SQL Server 2012
Application:
Web
Miscellaneous
Thread ID:
01621484
Message ID:
01621485
Views:
77
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
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform