user1926138
user1926138

Reputation: 1514

Optimize query of sql server

I want number of users present in a department.i have 9 department.

now i am using "while" loop to count no of users present in an department.

Can you please suggest how to count no of users present in an department.

Department table(Columns: Id and DeptName) User Table(Columns: Id, Name, deptId)

Please help me

Thanks

[EDIT]

User table
----------
id         name           deptid
1           a              1
2           b              1
3           c              2
4           d             null
5           e              3
6           f              4
7           g              2
8           h              4
9           i              5
10          j              5
11          k              null

Department
----------

id    name 
1      x
2      x1
3      y
4      y1
5      z
6      z1

Result
------
count    depetname
9         all
2         x
2         x1
1         y
2         y1
2         z
0         z1

[/EDIT]

Upvotes: 0

Views: 51

Answers (1)

mehdi
mehdi

Reputation: 1755

see DEMO

EDIT

you should be use RIGHT JOIN

select 'all', count(0) from users

union

SELECT department.name, COUNT(users.id) FROM users Right Outer JOIN department 
     ON users.deptId=department.id GROUP BY department.id

Upvotes: 1

Related Questions