I have a table with a complete list of all products as shown below:
Table "Products"
Item Code | Product Name |
---|---|
1001 | Model 1 |
1002 | Model 2 |
1003 | Model 3 |
1004 | Model 4 |
1005 | Model 5 |
1006 | Model 6 |
There is another table containing transactions of these products. Each item code can be in the table once, multiple times or not at all under same or different dates as shown below:
Table "Transactions"
Item Code | Date | Qty |
---|---|---|
1001 | 2025-01-31 | 50 |
1002 | 2025-01-31 | 100 |
1004 | 2025-01-31 | 35 |
1005 | 2025-01-31 | 80 |
1001 | 2025-02-28 | 40 |
1001 | 2025-03-31 | 60 |
1002 | 2025-03-31 | 70 |
1006 | 2025-03-31 | 10 |
I would like to get the list of all products from the Products table and then get corresponding latest record by date from transactions if available for each of the item code.
Result would look as below:
Includes all the item codes whether or not it has any transaction. Date is whichever the most recent and same qty from that date.
Result Set
Item Code | Date | Qty |
---|---|---|
1001 | 2025-03-31 | 60 |
1002 | 2025-03-31 | 70 |
1003 | null | null |
1004 | 2025-01-31 | 35 |
1005 | 2025-01-31 | 80 |
1006 | 2025-03-31 | 10 |
I am using the following query to join the multiple tables but having trouble on the latter statement:
SELECT a.itemcode, a.productname, b.date, b.qty FROM
(SELECT * FROM products) AS a LEFT JOIN
(SELECT * FROM transactions......) AS b ON a.itemcode = b.itemcode;
You can do something like the following where you perform left join to make sure all products are included and use MAX function to get the most recent date of transaction for that particular product. Then you can sort as needed (I've sorted by item code because that's what your result set looks like).
SELECT
p."Item Code",
t.Date,
t.Qty
FROM
"Products" p
LEFT JOIN "Transactions" t
ON p."Item Code" = t."Item Code"
AND t.Date = (
SELECT MAX(Date)
FROM "Transactions"
WHERE "Item Code" = p."Item Code"
)
ORDER BY p."Item Code";