简体   繁体   English

来自子选择查询的意外答案

[英]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 当我执行此查询时,所有出发部门都显示在depart_decode列中,那里的数字也= 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子句:

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. 仅当表Departments中存在Depart_code 151并且仅对该行存在时,此结果才为true。

Remove and Depart_code=151 and you should get your results. 删除and Depart_code=151 ,您应该得到结果。

Using correlated subqueries in a select clause is often a source of performance problems. select clause使用correlated subqueries通常是性能问题的根源。 I would recommend using a subquery to prepare the counts you want and just join that back to the department table. 我建议使用子查询来准备所需的计数,然后将其重新加入到Department表中。

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
;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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