简体   繁体   中英

Unexpected answer from query with sub-selects

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

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.

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
;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM