I have a table with the following (simplified) structure:
Order, Status, Sequence
1000, New, 0
1000, Viewed, 1
1000, Shipped, 2
1001, New, 0
1002, New, 0
1002, Viewed, 1
1002, New, 2
I want a SELECT statement that will return the row with the max sequence number for each order. So, in the above example, I would want the resulting dataset to be:
1000, Shipped, 2
1001, New, 0
1002, New, 2
Is there a simple way to do this? I can't seem to construct a WHERE expression that can do it.
To respond to a few comments:
since you haven't mentioned your RDBMS, you can try this query below,
SELECT a.*
FROM tableName a
INNER JOIN
(
SELECT Order, MAX(Sequence) maxValue
FROM tableName
GROUP BY Order
) b ON a.Order = b.Order AND
a.Sequence = b.maxValue
this works on most RDBMS.
if your RDBMS supports Window Function, you can do it like this,
SELECT Order, Status, Sequence
FROM
(
SELECT Order, Status, Sequence,
ROW_NUMBER() OVER (PARTITION BY Order
ORDER BY Sequence DESC)
FROM TableName
) derivedTable
remember that ORDER (also SEQUENCE but not all) is a reserved keyword and must be escaped. The escaped character should depend on what RDBMS you are using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With