我有以下数据要过滤,因此我只能根据第一列的分组获得一行并选择最大日期
co2 包含唯一值
col1 | col2 | date
1 | 123 | 2013
1 | 124 | 2012
1 | 125 | 2014
2 | 213 | 2011
2 | 214 | 2015
2 | 215 | 2018
所以我想要的结果是:
1 | 125 | 2014
2 | 215 | 2018
我已经尝试使用我在此处找到的一些示例(如下所示)以及/distinct/max(date) 的其他组,但没有运气
select t.*
from (select t.*,
row_number() over (partition by col1, col2 order by date desc) as seqnum
from t
) t
where seqnum = 1
最佳答案
更改 row_number()
中的分区仅按 col1
进行分区但保持订单date desc
:
select col1, col2, date
from
(
select col1, col2, date,
row_number() over (partition by col1
order by date desc) as rn
from yourtable
) x
where rn = 1
见 SQL Fiddle with Demo .
由于您同时按
col1
进行分区和 col2
您获得了每一行的唯一值。所以它不会返回具有最大日期的行。
关于sql - 按列和最大日期分组时如何选择单行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821811/