SQL:如何选择最早的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5736820/
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: How To Select Earliest Row
提问by dvanaria
I have a report that looks something like this:
我有一份看起来像这样的报告:
CompanyA Workflow27 June5
CompanyA Workflow27 June8
CompanyA Workflow27 June12
CompanyB Workflow13 Apr4
CompanyB Workflow13 Apr9
CompanyB Workflow20 Dec11
CompanyB Wofkflow20 Dec17
This is done with SQL (specifically, T-SQL version Server 2005):
这是通过 SQL(特别是 T-SQL 版本 Server 2005)完成的:
SELECT company
, workflow
, date
FROM workflowTable
I would like the report to show just the earliest dates for each workflow:
我希望报告仅显示每个工作流程的最早日期:
CompanyA Workflow27 June5
CompanyB Workflow13 Apr4
CompanyB Workflow20 Dec11
Any ideas? I can't figure this out. I've tried using a nested select that returns the earliest tray date, and then setting that in the WHERE clause. This works great if there were only one company:
有任何想法吗?我想不通。我尝试使用返回最早托盘日期的嵌套选择,然后在 WHERE 子句中进行设置。如果只有一家公司,这很有效:
SELECT company
, workflow
, date
FROM workflowTable
WHERE date = (SELECT TOP 1 date
FROM workflowTable
ORDER BY date)
but this obviously won't work if there is more than one company in that table. Any help is appreciated!
但如果该表中有不止一家公司,这显然行不通。任何帮助表示赞赏!
回答by Achim
Simply use min()
只需使用 min()
SELECT company, workflow, MIN(date)
FROM workflowTable
GROUP BY company, workflow
回答by Cade Roux
In this case a relatively simple GROUP BY
can work, but in general, when there are additional columns where you can't order by but you want them from the particular row which they are associated with, you can either join back to the detail using all the parts of the key or use OVER()
:
在这种情况下,一个相对简单的方法GROUP BY
可以工作,但一般来说,当您无法订购其他列但您希望它们来自与它们关联的特定行时,您可以使用所有关键部分或用途OVER()
:
Runnable example (Wofkflow20 error in original data corrected)
可运行示例(已更正原始数据中的 Wofkflow20 错误)
;WITH partitioned AS (
SELECT company
,workflow
,date
,other_columns
,ROW_NUMBER() OVER(PARTITION BY company, workflow
ORDER BY date) AS seq
FROM workflowTable
)
SELECT *
FROM partitioned WHERE seq = 1
回答by ypercube??
SELECT company
, workflow
, MIN(date)
FROM workflowTable
GROUP BY company
, workflow