tags:

views:

352

answers:

3

Hi everyone,

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  A: 

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
Marc Gravell
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...
Erebus
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.
Marc Gravell
+3  A: 

If you have multiple orderIDs in your table (and they each have different datetime values), which one do you want to choose? The newest date, oldest date, or something else?

Simon Righarts
A: 

Perhaps a CTE would help:

WITH CTE
AS
(

SELECT orderId FROM table ORDER BY datetime DESC

)

SELECT DISTINCT orderId  FROM CTE
unclepaul84
It's specific to SQL Server though, which may not be useful...
gbn
Thanks for the correction, for a moment i forgot that this is not the MSDN SQL forum :)
unclepaul84