我有以下数据,我想过滤,所以我只根据第一列的分组得到一行,并选择最大日期
co2包含唯一值
col1 | col2 | date
1 | 123 | 2013
1 | 124 | 2012
1 | 125 | 2014
2 | 213 | 2011
2 | 214 | 2015
2 | 215 | 2018
Run Code Online (Sandbox Code Playgroud)
所以我想要的结果是:
1 | 125 | 2014
2 | 215 | 2018
Run Code Online (Sandbox Code Playgroud)
我尝试过使用我在这里找到的几个例子(如下所示)以及其他组/ distinct/max(日期),但没有运气
select t.*
from (select t.*,
row_number() over (partition by col1, col2 order by date desc) as seqnum
from t
) t
where seqnum = 1
Run Code Online (Sandbox Code Playgroud)
将 中的分区更改为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
Run Code Online (Sandbox Code Playgroud)
请参阅SQL Fiddle 演示。
由于您同时按两者进行分区,col1并且col2每行都获得了唯一的值。因此它不会返回具有最大日期的行。
| 归档时间: |
|
| 查看次数: |
3328 次 |
| 最近记录: |