当我执行此查询时,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
答案 0 :(得分:1)
您的查询在每个子选择中包含此where子句:
where Depart_code=D.Depart_code and Depart_code=151
如果表Departments中存在Depart_code 151并且仅针对该行,则此计算结果为true。
删除and Depart_code=151
,您应该得到结果。
答案 1 :(得分:0)
在correlated subqueries
中使用select clause
通常是性能问题的根源。我建议使用子查询来准备您想要的计数,然后将其加入到部门表中。
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
;