SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Join Tables with limit
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

IDILIO49
Starting Member

1 Posts

Posted - 12/30/2012 :  00:48:43  Show Profile  Reply with Quote
I have 3 tables and need to do a join with the 3 but with a limit for one of them.
Lets say:
Table Persons
Table Cars
Table Childs

I want to see a line for every combination Person / Child / Car (but only for the last 4 cars)

This can be the query for all combinations

select p.name, c.name, r.name from Persons p, Childs c, Cars r where p.id=c.parentid and p.id=r.ownerid

but now the question is how can I limit this to show only combinations for the most recent 4 Cars.date for that Person?

sodeep
Flowing Fount of Yak Knowledge

USA
7174 Posts

Posted - 12/30/2012 :  10:01:05  Show Profile  Reply with Quote
Select p.name, c.name, r.name
from
(
Select p.name, c.name, r.name,ROW_NUMBER() OVER (PARTITION BY P.Name Order by r.date desc) as Seq
from Persons p
inner join Childs c on p.id = c.parentid 
inner join Cars r on p.id = r.ownerid
)T
Where T.Seq <=4
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000