ThatRickGuy
Programmer
Hey guys, this one has me scratching my head. The query should return a lease number and the amounts past due in 4 different time frames.
the rls table holds the lease information and the rar table is the accounts receivable. and unpaid invoice sits in the rar table. Each of the 4 sub querys, if run individually, works fine and brings back the exact amount due for that time frame. But when I put them all together with left joins, which ever subquery is listed first brings back the correct data, and the three others just copy that.
Should return:
is returning:
Any thoughts?
-Rick
----------------------
the rls table holds the lease information and the rar table is the accounts receivable. and unpaid invoice sits in the rar table. Each of the 4 sub querys, if run individually, works fine and brings back the exact amount due for that time frame. But when I put them all together with left joins, which ever subquery is listed first brings back the correct data, and the three others just copy that.
Should return:
Code:
Lease | Current | 30-60 | 60-90 | 90+
1 100 100 nul nul
2 100 100 200 nul
is returning:
Code:
Lease | Current | 30-60 | 60-90 | 90+
1 100 100 100 100
2 100 100 100 100
Any thoughts?
Code:
SELECT
rls.lse_s AS LeaseNum,
PastDue0To30Days.AmountDue1,
PastDue30To60Days.AmountDue2,
PastDue60To90Days.AmountDue3,
PastDue90PlusDays.AmountDue4
FROM
rls
LEFT JOIN
(SELECT
lse_s,
SUM(tamt_b_d) AS AmountDue1
FROM
rar
WHERE
d_pmtdu_s > DATEADD(dd, -30, getdate())
GROUP BY
lse_s) PastDue0To30Days
ON rls.lse_s = PastDue0To30Days.lse_s
LEFT JOIN
(SELECT
lse_s,
SUM(tamt_b_d) AS AmountDue2
FROM
rar
WHERE
d_pmtdu_s <= DATEADD(dd, -30, getdate()) AND
d_pmtdu_s > DATEADD(dd, -60, getdate())
GROUP BY
lse_s) PastDue30To60Days
ON rls.lse_s = PastDue30To60Days.lse_s
LEFT JOIN
(SELECT
lse_s,
SUM(tamt_b_d) AS AmountDue3
FROM
rar
WHERE
d_pmtdu_s <= DATEADD(dd, -60, getdate()) AND
d_pmtdu_s > DATEADD(dd, -90, getdate())
GROUP BY
lse_s) PastDue60To90Days
ON rls.lse_s = PastDue60To90Days.lse_s
LEFT JOIN
(SELECT
lse_s,
SUM(tamt_b_d) AS AmountDue4
FROM
rar
WHERE
d_pmtdu_s <= DATEADD(dd, -90, getdate())
GROUP BY
lse_s) PastDue90PlusDays
ON rls.lse_s = PastDue90PlusDays.lse_s
-Rick
----------------------