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:
- There are several DMBS in use where this problem arises: MS-SQL, MySQL, Oracle and Access.
- There are so many DMBSs involved because the system being developed is consolidating data from other databases in the organization. For this reason I have no control over column names that are reserved words but I am aware of the need to escape the names.
- Many combinations of subqueries, GROUP BY, DISTINCT, MAX and COUNT were tried to no success. Since the query results always end up in Excel I have being grabbing all the rows and sorting and removing duplicates in Excel. My preference is to skip this step by having the SQL query do the work.
SQL-pattern: finding_the_max can alway be expressed in terms of NOT EXISTS a bigger one: