So filter to include only those rows where the version is the highest version in it's sequence
Select id, version, sequence
From DataTable dt
where version =
(Select Max(version)
From DataTable
where Sequence = dt.Sequence)
Question
I have data like this :
ID VERSION SEQUENCE
-------------- -------------- ---------------
01-001 01 001
01-002 01 002
02-002 02 002
And I want to select only the higher version for each sequence in order to have a result like this :
ID VERSION SEQUENCE
-------------- -------------- ---------------
01-001 01 001
02-002 02 002
I think the request should contains a group by on Sequence, but I can't manage to make it work
Can someone help ?
Solution
So filter to include only those rows where the version is the highest version in it's sequence
Select id, version, sequence
From DataTable dt
where version =
(Select Max(version)
From DataTable
where Sequence = dt.Sequence)
OTHER TIPS
using a Common Table Expression you could:
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
You didn't specify your DBMS so this is 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;