SQL选择不同的值,但按其他值排序 [英] SQL Select Distinct Values, but order by a different value
问题描述
我想从表中选择所有不同的order_id,然后按日期列对列表进行排序。当然,使用DISTINCT是一个查询范围的参数,因此尝试执行以下操作是不起作用的:
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
这将返回所有DISTINCT组合的orderId和datetime,所以我剩下多个我不需要的orderId。因此,我认为DISTINCT子句不是可行的方法。有人对我如何解决此问题有任何建议吗?
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?
谢谢!
推荐答案
如果订单有多行,您要显示哪个日期?也许:
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
这篇关于SQL选择不同的值,但按其他值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!