Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
steve4819
Starting Member
1 Post |
Posted - 2008-12-16 : 13:21:44
|
| I have a table which contains contract schedules. The data looks like:contract_id contract_version sub_sequence product_id work_date activity_date3177 1 1 1234 01/01/08 02/07/083177 1 2 5678 01/02/08 01/08/083177 2 1 1234 01/03/08 NULL3177 2 2 5678 01/04/08 NULLI need to update the work_date for each product line in the most recent version (2) with the activity_date+6 months from the previous version.So in the example above the third record would have the work_date updated from 01/03/08 to 02/01/09I have the following script which does the job, but I wondered if there was a simpler or better way to achieve the same results!UPDATE scheduleSET work_date = (SELECT activity_date FROM schedule AS curr_schedule WHERE (contract_id = '3177') AND (contract_version = '2' - 1) AND (sub_sequence = (SELECT MAX(sub_sequence) AS Expr1 FROM schedule WHERE (contract_id = '3177') AND (contract_version = '2' - 1))) AND (product_id = schedule.product_id))WHERE (contract_id = '3177') AND (contract_version = '2') AND (sub_sequence = '1') AND (product_id IN (SELECT product_id FROM schedule WHERE (contract_id = '3177') AND (contract_version = '2' - 1) AND (sub_sequence = (SELECT MAX(sub_sequence) AS Expr1 FROM schedule WHERE (contract_id = '3177') AND (contract_version = '2' - 1)))))The script is to have the contract_id and version passed in as parameters eventually.Thanks |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-12-16 : 14:09:54
|
| [code]UPDATE tSET t.work_date=DATEADD(mm,6,t1.activity_date)FROm table tJOIN table t1ON t.contract_id=t1.contract_idAND t.product_id=t1.product_idAND t.contract_version=t1.contract_version+1[/code] |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-12-16 : 14:12:59
|
and just in case there happens to be gap in versions,use thisUPDATE tSET t.work_date=DATEADD(mm,6,t1.activity_date)FROM table tCROSS APPLY (SELECT TOP 1 activity_date FROM table WHERE contract_id=t.contract_idAND product_id=t.product_idAND contract_version<t.contract_versionORDER BY contract_version DESC)t1 |
 |
|
|
hanbingl
Aged Yak Warrior
652 Posts |
Posted - 2008-12-16 : 14:13:45
|
| [code]update a set work_date = dateadd(month,6,b.activity_date)from schedule a inner join schedule bon a.product_id = b.product_id and a.contract_version > b.contract_versionwhere a.contract_version = 2[/code] |
 |
|
|
|
|
|