Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Complex query: limit occurences of certain value

Status
Not open for further replies.

stuart1980

Programmer
Jul 30, 2002
1
AU
Lets say we have a 'person' table and a 'car' table. And the primary key for these tables are person_id and car_id respectively. A person can have many cars.

How could you select the first 3 cars for each person in ONE query? I don't want to requery for each person, nor do I want to filter the result set in my code.

Thanks in advance.
 
you didn't say what the fk from car to person was, so i'll call it car.owner_id

you didn't say what sequence "first 3" refers to, so i'll assume it's the date the car was acquired

i haven't tested this but i think i got the inequalities in the right direction :grin:

Code:
select person_id, car_id, car.acquired
  from person
inner
  join car X
    on person_id = car.owner_id
 where 3 > 
       ( select count(*) 
           from car
          where owner_id = person.person_id
            and acquired < X.acquired ) 
order 
    by person_id
     , car.acquired

the &quot;top n&quot; query (as that subquery is more commonly known) is a lot simpler if your database supports the TOP or LIMIT keyword

rudy
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top