1

I've previously asked how to use a sequence ID to select the most recently updated row, but I'm not quite sure how to apply it to a more advanced query involving multiple joins. Here is my current query:

select
 p.Person_ID,
 p.Person_Name,
 p.Person_Age,
 d.Department_Name,
 c.Company_Name,
 c.Company_City,
 c.Company_State
from Person p
left join Department d 
 on p.Person_Department_ID=d.Department_ID
left join (
 select Company_ID, Company_Name, Company_City, Company_State
 from Company
 group by Company_ID, Company_Name, Company_City, Company_State
) as c on c.Company_ID=d.Department_Company_ID
where c.Company_ID=1

I have made an example on SQLFiddle for this question. I want to only select the most recent Person (max(Person_Seq_ID)), and only show the most up-to-date Department name next to that Person (max(Department_Seq_ID)). There should only be seven records returned in my uploaded example. How do I do this?

Note that only Person and Department have sequence IDs—not Company.

asked Dec 11, 2013 at 22:45

1 Answer 1

3

Unless I missed something, the following will give you what is needed :

SELECT * FROM 
(
select
 p.Person_ID,
 p.Person_Name,
 p.Person_Age,
 d.Department_Name,
 c.Company_Name,
 c.Company_City,
 c.Company_State,
 p.Person_Seq_ID,
 d.Department_ID,
 d.Department_Seq_ID,
 MAX(p.Person_Seq_ID) OVER(PARTITION BY p.Person_ID) as mPerson,
 MAX(d.Department_Seq_ID) OVER(PARTITION BY p.Person_ID, d.Department_ID) as mDep
from Person p
left join Department d 
 on p.Person_Department_ID=d.Department_ID
left join (
 select Company_ID, Company_Name, Company_City, Company_State
 from Company
 group by Company_ID, Company_Name, Company_City, Company_State
) as c on c.Company_ID=d.Department_Company_ID
where c.Company_ID=1
 ) a 
WHERE Person_Seq_ID = mPerson and Department_Seq_ID = mDep

Here is an updated link showing this on SQLFiddle.

Dan
3005 silver badges16 bronze badges
answered Dec 11, 2013 at 23:36
4
  • I don't see the point of the subquery on Company. That can just be the company table itself, no? Commented Dec 11, 2013 at 23:57
  • Any way to make it not show all the keys at the end, though? Commented Dec 12, 2013 at 0:06
  • @Max Vernon : You are right , but I didn't pay attention to further optimization - focused on returning desired output. Commented Dec 12, 2013 at 14:53
  • @Dan : Absolutely, you can select any columns inside subquery(derived table) Commented Dec 12, 2013 at 14:53

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.