Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Query to find multiple records
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

United Kingdom
16 Posts

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

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?

Flowing Fount of Yak Knowledge

2875 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


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

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

Very Important crosS Applying yaK Herder

52326 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

Go to Top of Page
  Previous Topic Topic Next 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.02 seconds. Powered By: Snitz Forums 2000