I have this table structure and sample data. In this table there is sale order's iterations. At first Mouse was requested for 15 Qty. Later on buyer decides to update the Qty and make it 25 and then again later he realizes he only needs 20. So I want to get the most latest row for specific Item from sale order.
CREATE TABLE SaleOrder
(
ID INT PRIMARY KEY,
Item VARCHAR(25),
Qty INT
)
INSERT INTO SaleOrder VALUES (1, 'Mouse', 15);
INSERT INTO SaleOrder VALUES (2, 'Key Board', 10);
INSERT INTO SaleOrder VALUES (3, 'Printer', 3);
INSERT INTO SaleOrder VALUES (4, 'Mouse', 25);
INSERT INTO SaleOrder VALUES (5, 'Mouse', 20);
Here is the query I have wrote.
SELECT ID, Item, Qty
FROM SaleOrder M
WHERE ID = (SELECT MAX(ID) FROM SaleOrder S WHERE S.ID = M.ID GROUP BY Item)
The expected out put should contain 3 rows like this.
ID Item Qty
1 Mouse 15
2 Key Board 10
3 Printer 3
4 Mouse 25
5 Mouse 20
Is there something I am missing here ?