2014-04-25 60 views
1

我有這樣的數據:SQL,集團一列

ID    VERSION  SEQUENCE 
-------------- -------------- --------------- 
    01-001   01   001   
    01-002   01   002   
    02-002   02   002 

我要選擇,以便每個序列只有更高版本,有這樣的結果:

ID    VERSION  SEQUENCE 
-------------- -------------- --------------- 
    01-001   01   001    
    02-002   02   002 

我認爲這個請求應該包含一個由Sequence組成的組,但我無法設法使其工作

有人可以幫忙嗎?

回答

0

所以過濾結果只包括那些排在所述版本在它的最高版本的序列

Select id, version, sequence 
From DataTable dt 
where version = 
    (Select Max(version) 
    From DataTable 
    where Sequence = dt.Sequence) 
+0

非常感謝你:) – Chaguyot

0

使用公共表表達式您可以:

with HighestSequence(ID,MaxSequence) 
as 
(
    select id, max(Sequence) 
    from table 
    group by ID 
) 

select t.* 
from table t 
inner join HighestSequence hs 
on t.id = hs.id 
and t.sequence = hs.sequence 
0

你沒」 t指定你的DBMS,所以這是ANSI SQL:

select id, version, sequence 
from (
    select id, version, sequence, 
     row_number() over (partition by id order by sequence) as rn 
    from the_table 
) t 
where rn = 1 
order by id;