Simplified problem: In a table "table1" we have columns: RowID, ItemID, BranchID, RoomID, Date, Qty
I am trying to retrieve the last Qty of an ItemID in each RoomID in each BranchID.
Once I get this going the plan is to JOIN table1 to ItemIDTable, BranchIDTable, RoomIDTable to get names for IDs.
By using MAX(Date) I got as far as getting Qty for ItemID that are only in one RoomID, however if an ItemID is in multiple RoomID the function MAX(Date) returns the latest record among all rooms, while I need the latest for each room.
Data set for ItemID = 50 and BranchID = 4:
+--------+----------+--------+-----+---------------------+------------+------------+--------------+ | ItemID | BranchID | RoomID | Qty | Date | ItemIDName | RoomIDNAme | BranchIDName | +--------+----------+--------+-----+---------------------+------------+------------+--------------+ | 50 | 4 | 1 | 7 | 2019-12-12 13:30:15 | ItemA | RoomB | BranchB | | 50 | 4 | 2 | 5 | 2019-12-12 13:30:20 | ItemA | RoomA | BranchB | | 50 | 4 | 2 | 8 | 2019-12-12 13:30:25 | ItemA | RoomA | BranchB | +--------+----------+--------+-----+---------------------+------------+------------+--------------+
Results I get (it selected latest out of two RoomIDs):
+--------+----------+--------+-----+---------------------+------------+------------+--------------+ | ItemID | BranchID | RoomID | Qty | Date | ItemIDName | RoomIDNAme | BranchIDName | +--------+----------+--------+-----+---------------------+------------+------------+--------------+ | 50 | 4 | 2 | 8 | 2019-12-12 13:30:25 | ItemA | RoomA | BranchB | +--------+----------+--------+-----+---------------------+------------+------------+--------------+
Expected (latest Qty for each RoomID):
+--------+----------+--------+-----+---------------------+------------+------------+--------------+ | ItemID | BranchID | RoomID | Qty | Date | ItemIDName | RoomIDNAme | BranchIDName | +--------+----------+--------+-----+---------------------+------------+------------+--------------+ | 50 | 4 | 1 | 7 | 2019-12-12 13:30:15 | ItemA | RoomB | BranchB | | 50 | 4 | 2 | 8 | 2019-12-12 13:30:25 | ItemA | RoomA | BranchB | +--------+----------+--------+-----+---------------------+------------+------------+--------------+
The query itself:
SELECT table1.ItemID, table1.BranchID, table1.RoomID, table1.Qty, table1.Date, ItemIDTable.ItemIDName, RoomIDTable.RoomIDName, BranchIDTable.BranchIDName FROM table1 INNER JOIN ItemIDTable ON table1.ItemID = ItemIDTable.ItemID INNER JOIN RoomIDTable ON table1.RoomID = RoomIDTable.RoomID INNER JOIN BranchIDTable ON table1.BranchID = BranchIDTable.BranchID WHERE (table1.Date IN ( SELECT MAX(Date) FROM table1 WHERE (ItemID = table1.ItemID) AND (BranchID = table1.BranchID) ) ) ORDER BY table1.ItemID
I've tried to shorten and simplify titles to make it more readable. A would appreciate any insights into this, whether to make this query work or use a better method.