Reputation: 1
When I execute this query then all departs shown in depart_decode
column and there figures also =Nil
select D.depart_decode
(select count (Staff_NO) from AA.table where Depart_code=D.Depart_code and Depart_code=151 and Staff_Sub_NO=5) Manager,
(select count (Staff_NO) from AA.table where Depart_code=D.Depart_code and Depart_code=151 and Staff_Sub_NO=4) HOD,
(select count (Staff_NO) from AA.table where Depart_code=D.Depart_code and Depart_code=151 and Staff_Sub_NO=3) Head,
(select count (Staff_NO) from AA.table where Depart_code=D.Depart_code and Depart_code=151 and Staff_Sub_NO in(1,2)) staff
from AA.Departments D
Upvotes: 0
Views: 83
Reputation: 35593
Using correlated subqueries
in a select clause
is often a source of performance problems. I would recommend using a subquery to prepare the counts you want and just join that back to the department table.
SELECT
D.depart_decode, c.Manager, c.Hod, c.Head, c.staff
FROM AA.Departments D
INNER JOIN (
SELECT
Depart_code
, COUNT(CASE WHEN Staff_Sub_NO = 5 THEN Staff_NO END) Manager
, COUNT(CASE WHEN Staff_Sub_NO = 4 THEN Staff_NO END) HOD
, COUNT(CASE WHEN Staff_Sub_NO = 3 THEN Staff_NO END) Head
, COUNT(CASE WHEN Staff_Sub_NO < 3 THEN Staff_NO END) staff
FROM AA.table
GROUP BY
Depart_code
) C ON D.Depart_code = C.Depart_code
;
Upvotes: 0
Reputation: 2808
You query contains this where clause in each subselect:
where Depart_code=D.Depart_code and Depart_code=151
This evaluates to true only, if a Depart_code 151 exists in table Departments and only for that row.
Remove and Depart_code=151
and you should get your results.
Upvotes: 1