SQL 选择不同的值,但按不同的值排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1785501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Select Distinct Values, but order by a different value
提问by Erebus
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:
我想从我的表中选择所有不同的 order_ids,并按日期列对该列表进行排序。使用 DISTINCT 当然是一个查询范围的参数,所以尝试这样的事情是行不通的:
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?
这将返回 orderId 和 datetime 的所有 DISTINCT 组合,因此我留下了多个我不想要的 orderId。因此,我认为 DISTINCT 子句不是要走的路。有没有人对我如何解决这个问题有任何建议?
Thanks!
谢谢!
回答by Marc Gravell
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
回答by unclepaul84
Perhaps a CTE would help:
也许 CTE 会有所帮助:
WITH CTE
AS
(
SELECT orderId FROM table ORDER BY datetime DESC
)
SELECT DISTINCT orderId FROM CTE
回答by jank
SELECT DISTINCT * FROM
(SELECT value1
FROM table1
ORDER BY value2);
That worked for me.
那对我有用。