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
 Query to find multiple records
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

105ben
Starting Member

United Kingdom
16 Posts

Posted - 01/02/2013 :  17:31:39  Show Profile  Reply with Quote
Hello,

I need to write a query that will look in a table and return the user ID of a person who has been allocated for all of the departments. The tables look like:

PERSON(person_id, person_name)
ALLOCATION(alloc_id, person_id, dep_id, date_start, date_end)
DEPARTMENT(dep_id, dep_name)

There are 4 departments, with ID's of 1,2,3 and 4. I cannot use a count, as the person may quit a dept. then work for it again meaning the count will return 2, when theyve only really worked for 1...

Does anybody know how I would go about this?

jimf
Flowing Fount of Yak Knowledge

USA
2869 Posts

Posted - 01/02/2013 :  17:54:32  Show Profile  Reply with Quote
SELECT p.Person_id,p.person_name
FROM person p
INNER JOIN ALLOCATION a on p.person_id = a.person_id
INNER JOIN DEPARTMENT d on a.dep_id = d.dep_id
GROUP BY p.Person_id,p.person_name
HAVING COUNT(distinct dep_id) = 4

Jim

Everyday I learn something that somebody else already knew
Go to Top of Page

105ben
Starting Member

United Kingdom
16 Posts

Posted - 01/02/2013 :  18:05:49  Show Profile  Reply with Quote
Thanks Jim! Appreciate that!

How come both person_id and person_name are in the group by column, just out of curiosity?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 01/03/2013 :  00:51:26  Show Profile  Reply with Quote
if you want to select both of columns they both need to be in GROUP BY. It doesnt cause any problem as person_id to person_name relationship would always be 1 to 1

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

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.06 seconds. Powered By: Snitz Forums 2000