表:
+------------+------------------+
| 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
答案 0 :(得分:4)
您需要使用带有 max()
的聚合函数GROUP BY
:
SELECT number, max(date)
from yourtable
group by number
根据您的数据库,您可以使用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
这也可以使用子查询编写:
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;