2013-04-04 48 views
5

我有我想過濾下面的數據,所以我只得到基於第一列的分組只有一行,並選擇最多的日期如何按列和最大日期分組時選擇單個行?

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 

我使用,我發現放在這裏(如下)的幾個例子,以及另一組由/獨特/ 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 

回答

3

變化由col1分區的row_number()只有分區,但通過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

既然您是通過col1col2進行分區的,您將獲得每行的唯一值。所以它不會返回最大日期的行。

+0

將這項工作中[標籤:甲骨文]? – Kermit 2013-04-04 21:18:06

+1

@FreshPrinceOfSO是的 – Taryn 2013-04-04 21:18:24

+0

[那麼](http://cf.chucklesnetwork.agj.co/items/1/4/0/4/i-dont-always-upvote_but-when-i-do-i-have- to-t.jpg) – Kermit 2013-04-04 21:19:14

0

我喜歡bluefeet的方法,但這裏是等效採用MAX:

SELECT t.col1, t.col2, t.date 
FROM yourtable t 
    JOIN (
     SELECT col1, MAX(date) maxDate 
     FROM yourtable 
     GROUP BY col1 
    ) t2 on t.col1 = t2.col1 AND t.date = t2.maxDate 

SQL Fiddle Demo(從其他崗位借用)

0
Select * from yourtable where date in 
(select max(date) from tab group by col1);