2012-11-19 48 views
0

我有兩個表,我想加入和過濾數據。我用一個存儲過程來做到這一點。我的意圖是從第二張表(即部門)中提取每個項目,即使他們在第一個表格(即員工)中沒有匹配的記錄並最終顯示計數。以下是我使用的代碼段:右外連接問題

select d.deptName, 
case when COUNT(*) is null then '0' else count(*) end AS total 
from Employee e 
right outer join Department d on e.deptID=d.deptID 
WHERE [email protected] 
and [email protected] 
group by d.deptName 
order by d.deptName 

但是,它沒有顯示我想要的內容,但未能找出真正的問題。

回答

1

當您在join之後通過where子句應用篩選條件時,它會篩選出所有不符合篩選條件的記錄。嘗試在移動篩選條件加盟條件本身如下:

select d.deptName, 
     case when COUNT(*) is null then '0' else count(*) end AS total 
    from Employee e 
    right outer join Department d 
     on ([email protected] 
      and [email protected] 
      and e.deptID=d.deptID) 
    group by d.deptName 
    order by d.deptName 
0

我認爲你需要改變這樣的

SELECT d.deptName, COUNT(e.deptID) AS total 
    FROM Employee e 
    RIGHT OUTER JOIN Department d 
     ON (e.Year= @year 
      AND e.Month= @month 
      AND e.deptID=d.deptID) 
    GROUP BY d.deptName 
    ORDER BY d.deptName 

代碼參見SQL搗鼓查詢:http://sqlfiddle.com/#!3/b1105/17

+0

是的,這查詢是很正確的,你可以使用它。 –