I have this query which groups the results by ORDER#.
SELECT ORDER#, MAX(SHIPDATE - ORDERDATE) DELAYDAYS FROM ORDERS GROUP BY ORDER#;
My goal is to return the single ORDER# that has the longest shipping delay. Not the entire set. How can I accomplish this?
Tried this too. Does not work. This gives me the single column, but not the ORDER#.
SELECT MAX(X.DELAYDAYS) FROM
(SELECT ORDER#, MAX(SHIPDATE - ORDERDATE) DELAYDAYS
FROM ORDERS GROUP BY ORDER#) X;
To get a list of all orders that tie for the longest delay:
Use the query below to get a single order, taking the lowest order# in case of a tie for the longest delay. (should always strive for a determinant result) I believe this is the optimal solution, requiring only one pass through the data.
To take the highest order# in case of a tie for longest delay, then simply use
max(order#)instead.Edit – I knew there was a better way. It just took a wile. I was hung up thinking I had to determine the max delay for each order#, but then I realized it wasn’t necessary for this query.