13

I want to select all distinct order_ids from my table, and order that list by the date column. Using DISTINCT is of course a query-wide parameter, so trying something like this doesn't work:

SELECT DISTINCT(orderId, datetime) 
FROM table 
ORDER BY datetime DESC

This returns all DISTINCT combinations of the orderId and datetime, so I'm left with multiple orderIds, which I don't want. Therefore I'm thinking that the DISTINCT clause is not the way to go. Does anyone have any suggestions on how I could solve this problem?

Thanks!

3 Answers 3

23

If there are multiple rows for the order, which date do you want to show? perhaps:

SELECT [orderId], MAX([datetime])
FROM [table]
GROUP BY [orderId]
ORDER BY MAX([datetime]) DESC
Sign up to request clarification or add additional context in comments.

2 Comments

As a follow up, what if I wanted to select all values in the table, not just orderId and datetime? I have a feeling that's a totally separate questions, but...
You would need to either aggregate all the columns, or select a particular row (min(id), max(id), or similar) and do a join / sub-query.
3

Perhaps a CTE would help:

WITH CTE
AS
(

SELECT orderId FROM table ORDER BY datetime DESC

)

SELECT DISTINCT orderId  FROM CTE

3 Comments

Thanks for the correction, for a moment i forgot that this is not the MSDN SQL forum :)
Says "The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.".
Does SQL Server guarantee the ordering of the CTE to be maintained? Seems like a very risky internal thing to rely on, if it even works. Especially since there are formally correct solutions, that guarantee the desired outcome.
0
SELECT DISTINCT * FROM 
  (SELECT value1 
   FROM table1 
   ORDER BY value2);

That worked for me.

1 Comment

This is incorrect. The database is free to ignore the derived table's ORDER BY clause, which it will effectively do when DISTINCT is implemented using hashing, e.g. in a more complex query. Your concrete database optimiser implementation may have accidentally produced the desired result, but you must not rely on it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.