0

桌子:

+------------+------------------+
|     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      |
+------------+------------------+------------+

我想在 GROUP 的日期 = MAX 时选择 DISTINCT 数字。

所以在查询之后我会得到:

1...b

2...b
4

1 回答 1

4

您将需要使用具有以下功能的聚合max()函数GROUP BY

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

请参阅带有演示的 SQL Fiddle

根据您的数据库,您可以使用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

于 2013-03-05T23:06:35.620 回答