[英]Unexpected answer from query with sub-selects
當我執行此查詢時,所有出發部門都顯示在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
您查詢的每個子選擇中都包含以下where子句:
where Depart_code=D.Depart_code and Depart_code=151
僅當表Departments中存在Depart_code 151並且僅對該行存在時,此結果才為true。
刪除and Depart_code=151
,您應該得到結果。
在select clause
使用correlated subqueries
通常是性能問題的根源。 我建議使用子查詢來准備所需的計數,然后將其重新加入到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.