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

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Couting certain join records

Author  Topic 

deco10
Starting Member

28 Posts

Posted - 2010-12-01 : 18:44:31
I posted this question and then deleted it because my example was terrible.

This the query I'm trying to get working

I want to find all of the events that have either
a) no people
b) no people with the person_category of 2
c) a count of the events with no person of type 2


SELECT count(*) as cnt, events.id, people.person_category_id, event_people.*
FROM events
INNER JOIN event_people ON events.id = event_people.event_id
INNER JOIN people ON people.id = event_people.person_id
GROUP by YEAR(events.start_date), MONTH(events.start_date)
HAVING people.person_category_id NOT IN (2)
ORDER BY events.id


The following should output something like the following:

2010 Jan - count:10
month year - number of events with no person of category 2
...
...
...
2010 Aug - count:3

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-12-01 : 19:25:44
You haven't provided sample data from your tables to illustrate the issue. You've provided the expected output, but not the starting data.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

deco10
Starting Member

28 Posts

Posted - 2010-12-01 : 20:02:36
My applogies, I thought it was discernable from the query.
Let me know if more detail is required.

In the example below I would want the query to return event with id=2 because that event has no event_people where the person.person_category is equal to 2

Here is my table layout:

events:
id, start_date
1, 2005-10-01
2, 2005-11-04
3, 2006-04-02

people:
id, name, birthdate, person_category_id
1, Dave, 1950-10-04, 2
2, Mike, 1958-11-13, 1
3, Lisa, 1967-07-25, 3
4, Stef, 1961-01-05, 4

event_people:
event_id, person_id,
1,1
1,2
2,2
2,3
2,4
3,1
3,4
Go to Top of Page
   

- Advertisement -