如何通过SQL中的MAX()进行分组?

时间:2013-03-05 23:04:29

标签: sql tsql

表:

+------------+------------------+
|     Number |       Date       |
+------------+------------------+
|          1 | 1900-01-01       |
|          1 | 2012-01-01       |
|          1 | 2011-01-01       |
|          2 | 1900-01-01       |
|          2 | 2007-01-01       |
+------------+------------------+

结果必须是:

+------------+------------+
|     Number |    Date    |
+------------+------------+
|          1 | 2012-01-01 |
|          2 | 2007-01-01 |
+------------+------------+

依旧......

编辑 -

表:

+------------+------------------+------------+
|     Number |       Date       |   Field3   |
+------------+------------------+------------+
|          1 | 1900-01-01       |     a      |
|          1 | 2012-01-01       |     b      |
|          1 | 2011-01-01       |     c      |
|          2 | 1900-01-01       |     a      |
|          2 | 2007-01-01       |     b      |
+------------+------------------+------------+

我想选择数字的DISTINCT WHERE它是GROUP的Date = MAX。

所以在查询后我会得到:

1...b

2...b

1 个答案:

答案 0 :(得分:4)

您需要使用带有max()的聚合函数GROUP BY

SELECT number, max(date)
from yourtable
group by number

SQL Fiddle with Demo

根据您的数据库,您可以使用row_number()

select number, date
from
(
  select number, date,
    row_number() over(partition by number order by date desc) rn
  from yourtable
) src
where rn = 1

请参阅SQL Fiddle with Demo

这也可以使用子查询编写:

select t1.*
from yourtable t1
inner join
(
  SELECT number, max(date) MaxDate
  from yourtable
  group by number
) t2
  on t1.number = t2.number
  and t1.date = t2.maxdate;

请参阅SQL Fiddle with Demo