I need to join two tables with similar data but don't uniformly line up. Here is a sample
Pay Table:
ID PayIndex PayDate Payment PayRate
1 0 2002-10-17 00:00:00.000 574028.7 0.0339
1 1 2003-02-18 00:00:00.000 875637 0.0339
1 2 2003-08-15 00:00:00.000 875637 0.0339
1 3 2004-02-17 00:00:00.000 875637 0.0339
...
1 11 2008-02-15 00:00:00.000 754020.75 0.0339
Rec Table:
ID RecIndex RecDate Reciept RecRate
1 0 2002-10-17 00:00:00.000 30952.6809374938 0.0143798749999971
1 1 2002-11-01 00:00:00.000 63968.8739374873 0.0143798749999971
1 2 2002-12-02 00:00:00.000 63968.8739374873 0.0143798749999971
...
1 11 2003-09-02 00:00:00.000 59841.8498124881 0.0143798749999971
...
1 70 2008-08-01 00:00:00.000 54955.8878402668 0.0143798749999971
Here is a sample of the result I want:
ID SortIndex Payment RecRate RecDate Reciept RecRate
1 0 -574028.7 0.0339 2002-10-17 30952.6809374938 0.0143798749999971 2002-10-17
1 1 -875637 0.0339 2003-02-18 63968.8739374873 0.0143798749999971 2002-11-01
1 2 -875637 0.0339 2003-08-15 63968.8739374873 0.0143798749999971 2002-12-02
...
1 10 -754020.75 0.0339 2007-08-15 66032.3859999868 0.0143798749999971 2003-08-01
1 11 -754020.75 0.0339 2008-02-15 59841.8498124881 0.0143798749999971 2003-09-02
1 12 NULL NULL NULL 68095.8980624864 0.0143798749999971 2003-10-01 NULL
1 13 NULL NULL NULL 57778.3377499885 0.0143798749999971 2003-11-03 NULL
...
1 69 NULL NULL NULL 55084.3081128363 0.0143798749999971 2008-07-01 NULL
1 70 NULL NULL NULL 54955.8878402668 0.0143798749999971 2008-08-01 NULL
I am currently able to get this result for one ID but not for the whole table with the folloiwing query:
SELECT Rec.SwpID, Rec.RecIndex AS SortIndex, Pay.Payment * -1 As Payment, Pay.PayRate, Pay.PayDate, Rec.Reciept, Rec.RecRate, Rec.RecDate
FROM [#SwpPay] as Pay Full Outer JOIN
[#SwpRec] as Rec ON Pay.SwpID = Rec.SwpID
AND Rec.RecIndex = Pay.PayIndex
where Rec.SwpID = 2251 OR Pay.SwpID = 2251
Order by Rec.SwpID, Rec.RecIndex
How do I write the query for all ID's?
An additional note is that the Pay or Rec could have more items and even the same number.
Start Free Trial