SQL Select Distinct Values, but order by a different value

为君一笑 提交于 2019-12-10 01:17:34

问题


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!


回答1:


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



回答2:


Perhaps a CTE would help:

WITH CTE
AS
(

SELECT orderId FROM table ORDER BY datetime DESC

)

SELECT DISTINCT orderId  FROM CTE



回答3:


SELECT DISTINCT * FROM 
  (SELECT value1 
   FROM table1 
   ORDER BY value2);

That worked for me.



来源:https://stackoverflow.com/questions/1785501/sql-select-distinct-values-but-order-by-a-different-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!