Author |
Topic |
wldodds
Starting Member
20 Posts |
Posted - 2013-09-05 : 08:43:22
|
I have 2 tables with the following data:select Year1, PeriodId from TableA----------------------Year1, PeriodId----------------------2013, 02013, 12013, 22013, 32014, 02014, 12014, 22014, 32014, 4select Actindx, Year1, PeriodId, Balance from TableB-----------------------------------Actindx, Year1, PeriodId, Balance-----------------------------------1, 2013, 0, 329821, 2013, 2, 15241, 2013, 3, 28971, 2014, 1, 4571, 2014, 4, 3655What I'm trying to get as a result set is the following:-------------------------------------Actindx, Year1, PeriodId, Balance -------------------------------------1, 2013, 0, 329821, 2013, 1, 329821, 2013, 2, 15241, 2013, 3, 28971, 2014, 0, 28971, 2014, 1, 4571, 2014, 2, 4571, 2014, 3, 4571, 2014, 4, 3655I tried a left outer join but it seems to only return values where periodid and year1 match.I know this isn't that complicated, any help is greatly appreciated.Thanks |
|
James K
Master Smack Fu Yak Hacker
3873 Posts |
Posted - 2013-09-05 : 08:50:06
|
You should do something like shown below. I may not have the conditions in the WHERE clause exactly right. If this does not give you the right answers, try adjusting those conditions to meet the criteria that you are looking for:SELECT b.actindx, a.year1, a.periodid, b.balanceFROM TableA a OUTER APPLY ( SELECT TOP (1) actindex, Balance FROM TableB b WHERE b.year1 = a.year1 AND b.PeriodId <= a.PeriodId ORDER BY PeriodId DESC ) b; |
|
|
|
|
|