I\'m trying to select only the row with the highest seq for each ID
ID | Seq | Age
-------------------
A 1 20
A 2 30
B
Assuming SQL-Server ( >= 2005) or Oracle (10g?):
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Seq DESC) AS RN
, ID, Age
FROM
Persons
)
SELECT ID, Age
FROM CTE
WHERE RN = 1
ROW_NUMBER returns the sequential number of a row within a partition of a result set.
Edit: works also in Oracle as you can see here: http://sqlfiddle.com/#!4/b7e79/2/0
In general, you neeed to use windowing or ranking functions - Rank()
, Row_number()
, etc.
select *
from
(
select *, row_number() over (partition by id order by age desc) rn
from yourtable
) v
where rn = 1
This will work in SQL Server 2005+ - in oracle you may need to specify the field names explicitly, instead of the *
Just in case you use an RDBMS that doesn't support window functions, you can use:
SELECT Persons.ID, Persons.Age, Persons.Seq
FROM Persons
INNER JOIN
( SELECT Persons.ID, MAX(Seq) AS Seq
FROM Persons
GROUP BY Persons.ID
) MaxP
ON MaxP.ID = Persons.ID
AND MaxP.Seq = Persons.Seq
It still involves a subquery, but I don't see a way of doing this without one, nor do I really understand why you would want to avoid them.