I need to join two tables to get the results I'm looking for. I've been working on this since yesterday and can't figure out whether or not I can achieve what I need in one query. I need to select ALL records that meet the DATE criteria from TABLE_A and ONLY the records that meet the DATE criteria from TABLE_B. TABLE_A only has one record per ITEM, but TABLE_B can have multiple records for the same ITEM, so I need to total the PAYMT field in TABLE_B.
My Data:
TABLE_A
ITEM AMOUNT DATE
1 300.00 20080605
2 200.00 20080605
3 100.00 20090215
TABLE_B
ITEM PAYMT DATE
1 200.00 20080910
1 50.00 20081017
1 50.00 20090331
2 200.00 20090331
3 100.00 20090815
My Query:
SELECT
TABLE_A.ITEM,
TABLE_A.AMOUNT,
TABLE_A.AMOUNT - SUM(TABLE_B.PAYMT) as REMAINING
FROM
TABLE_A LEFT OUTER JOIN TABLE_B ON TABLE_A.ITEM = TABLE_B.ITEM
WHERE
(TABLE_A.DATE <= 20090115 AND TABLE_B.DATE <= 20090115)
GROUP BY
TABLE_A.ITEM,
TABLE_A.AMOUNT
Expected result:
ITEM AMOUNT REMAINING
1 300.00 50.00
2 200.00 200.00
Actual result:
ITEM AMOUNT REMAINING
1 300.00 50.00
My Data:
TABLE_A
ITEM AMOUNT DATE
1 300.00 20080605
2 200.00 20080605
3 100.00 20090215
TABLE_B
ITEM PAYMT DATE
1 200.00 20080910
1 50.00 20081017
1 50.00 20090331
2 200.00 20090331
3 100.00 20090815
My Query:
SELECT
TABLE_A.ITEM,
TABLE_A.AMOUNT,
TABLE_A.AMOUNT - SUM(TABLE_B.PAYMT) as REMAINING
FROM
TABLE_A LEFT OUTER JOIN TABLE_B ON TABLE_A.ITEM = TABLE_B.ITEM
WHERE
(TABLE_A.DATE <= 20090115 AND TABLE_B.DATE <= 20090115)
GROUP BY
TABLE_A.ITEM,
TABLE_A.AMOUNT
Expected result:
ITEM AMOUNT REMAINING
1 300.00 50.00
2 200.00 200.00
Actual result:
ITEM AMOUNT REMAINING
1 300.00 50.00