简体   繁体   中英

T-SQL 2008 INSERT dummy row WHEN condition is met

**Schema & Dataset**

id version payment name
1 1 10 Rich
2 1 0 David
3 1 10 Marc
4 1 10 Jess
5 1 0 Steff

1 2 10 Rich
2 2 0 David
3 2 10 Marc
4 2 10 Jess
5 2 0 Steff

2 3 0 David
3 3 10 Marc
4 3 10 Jess

http://sqlfiddle.com/#!3/1c457/18 - Contains my schema and the dataset I'm working with.

Background

The data above is the final set after a stored proc has done it's processing so everything above is in one table and unfortunately I can't change it.

I need to identify in the dataset where a person has been deleted with a payment total greater than 0 in previous versions and insert a dummy row with a payment of 0. So in the above example, Rich has been deleted in version 3 with a payment total of 10 on previous versions. I need to first identify where this has happened in all instances and insert a dummy row with a 0 payment for that version. Steff has also been deleted on version 3 but she hasn't had a payment over 0 on previous versions so a dummy row is not needed for her.

Tried so far - So I looked at pinal dave's example here and I can look back to the previous row which is great so it's a step in the right direction. I'm not sure however of how to go about achieving the above requirement. I've been toying with the idea of a case statement but I'm not certain that would be the best way to go about it. I'm really struggling with this one and would appreciate some advice on how to tackle it.

You can do this by generating all possible combinations of names and versions. Then filter out the ones you don't want according to the pay conditions:

select n.name, v.version, coalesce(de.payment, 0) as payment
from (select name, max(payment) as maxpay from dataextract group by name) n cross join
     (select distinct version from dataextract) v left outer join
     dataextract de
     on de.name = n.name and de.version = v.version
where de.name is not null or n.maxpay > 0;

Here is a SQL Fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM