SQL:如何选择最早的行

时间:2011-04-20 21:24:28

标签: sql date select subset

我的报告看起来像这样:

CompanyA      Workflow27     June5
CompanyA      Workflow27     June8
CompanyA      Workflow27     June12
CompanyB      Workflow13     Apr4
CompanyB      Workflow13     Apr9
CompanyB      Workflow20     Dec11
CompanyB      Wofkflow20     Dec17

这是通过SQL(特别是T-SQL版本Server 2005)完成的:

SELECT company
   , workflow
   , date
FROM workflowTable

我希望报告能够显示每个工作流程的最早日期:

CompanyA      Workflow27     June5
CompanyB      Workflow13     Apr4
CompanyB      Workflow20     Dec11

有什么想法吗?我无法弄清楚这一点。我尝试使用嵌套选择返回最早的托盘日期,然后在WHERE子句中设置它。如果只有一家公司,这很有效:

SELECT company
   , workflow
   , date
FROM workflowTable
WHERE date = (SELECT TOP 1 date
              FROM workflowTable
              ORDER BY date)

但如果该表中有多个公司,这显然不起作用。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:43)

只需使用min()

即可
SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

答案 1 :(得分:20)

在这种情况下,一个相对简单的GROUP BY可以正常工作,但一般来说,如果有其他列无法按顺序排列,但是您希望它们与它们相关联的特定行,则可以使用密钥的所有部分联接回详细信息或使用OVER()

Runnable example (Wofkflow20 error in original data corrected)

;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

答案 2 :(得分:8)

SELECT company
   , workflow
   , MIN(date)
FROM workflowTable
GROUP BY company
       , workflow