You can do it like this:
SELECT a.carid, a.engine, a.version
FROM cars a
WHERE a.engine='6 cylinder' and
not exists (select 1
from cars c2
where c2.carid = a.carid and
c2.engine = a.engine and
c2.version > a.version
);
This assume you are trying to get the highest version for a given engine for a given carid.
Actually, you can do the same thing with the not in
version. The not exists
often performs better. If you care about performance, be sure you have an index on cars(engine, carid, version)
.
EDIT:
If you want the cars that have ever had a particular engine (and the most recent version, then do:
SELECT a.carid, a.engine, a.version
FROM cars a
WHERE not exists (select 1
from cars c2
where c2.carid = a.carid and
c2.version > a.version
) and
exists (select 1 from cars c2 where c2.carid = a.carid and c2.engine = '6 cylinder');
Another way of doing this might make sense in this case:
select a.*
from cars a join
(select carid, max(version) as maxversion
from cars
group by carid
having sum(c2.engine = '6 cylinder') > 0
) cc
on a.carid = cc.carid and a.version = cc.maxversion;
EDIT II:
If you wanted to do this with analytic functions:
select c.*
from (select c.*,
max(version) over (partition by carid) as maxversion,
sum(case when c.engine = '6 cylinder' then 1 else 0 end) over (partition by carid) as Num6Cylinder
from cars c
) c
where version = maxversion and Num6Cylinder > 0;
I'm not sure this is a great simplification.