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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 group by should show numbers with 0

Author  Topic 

esthera
Master Smack Fu Yak Hacker

1410 Posts

Posted - 2010-12-29 : 04:50:19
when i run a sql with a group by

like

select count(id),school from users group by school

now i want this to show the school and number of users but I also want to see if a school has 0 users

how do I do this?

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-29 : 04:55:36
select count(u.id),s.school
from schools s
left join users
on s.school = u.school
group by s.school


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

esthera
Master Smack Fu Yak Hacker

1410 Posts

Posted - 2010-12-29 : 05:33:51
a left join isn't doing it as if the school doesn't exist in my user table within my where clause then it doesn't return
Go to Top of Page

nigelrivett
Master Smack Fu Yak Hacker

3385 Posts

Posted - 2010-12-29 : 05:42:51
Which where clause?
Move references to the users table from the where clause into the join clause.


==========================================
Cursors are useful if you don't know sql.
SSIS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-12-29 : 06:19:04
quote:
Originally posted by esthera

a left join isn't doing it as if the school doesn't exist in my user table within my where clause then it doesn't return


Can you post the query you used?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

esthera
Master Smack Fu Yak Hacker

1410 Posts

Posted - 2010-12-29 : 07:00:20
the probelm is it's not as simple as i put it - I was tryting to amke simpler

select count(p.id) from users u left join teachers p on p.userid=u.id
left join school s on s.schoolid=p.schoolid group by s.schoolid
where mainprogram='xxxx'
now if there is no record in teacher for that main program I want it to return 0 but it's not even returning the schoolid
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2010-12-29 : 08:22:18
Try changing where to and

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -