如何选择组中具有最大值的行?

时间:2012-02-26 05:23:31

标签: sql sql-server sql-server-2008 tsql greatest-n-per-group

我有一张表,包含一系列任务:

ID      TaskName       Date
----------------------------------
1       Task1          2010-11-23
2       Task2          2011-12-01
3       Task1          2012-02-01
4       Task3          2008-01-09
5       Task2          2007-03-09
6       Task3          2000-01-01

如何创建一个视图包含具有最新执行日期的任务?

例如,上表的结果应为:

id  taskname  date
------------------------
3   Task1     2012-02-01
2   Task2     2011-12-01
4   Task3     2008-01-09

2 个答案:

答案 0 :(得分:2)

SELECT
  ID,
  TaskName,
  Date
FROM
(
  select 
    ID,
    ROW_NUMBER() OVER (PARTITION BY TaskName ORDER BY Date DESC) Ordinal,
    TaskName,
    Date
  FROM YourTable
) t
WHERE Ordinal = 1

答案 1 :(得分:0)

SELECT id, taskName, MAX(Date)
FROM table
GROUP BY taskName

(这在Oracle中不起作用,因为id不在GROUP BY中)