右外连接问题

时间:2012-11-19 04:00:08

标签: sql sql-server-2008 stored-procedures join outer-join

我有两个表要加入并过滤数据。我使用存储过程来做到这一点。我的意图是从第二个表格(即部门)带来每个项目,即使他们在第一个表格(即员工)中没有匹配的记录,并最终显示计数。以下是我使用的代码段:

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 e.Year=@year
and e.Month=@month
group by d.deptName
order by d.deptName

但是,它没有显示我想要的东西,也没有找出真正的问题。

2 个答案:

答案 0 :(得分:1)

where之后通过join子句应用过滤条件时,它会过滤掉所有不满足过滤条件的记录。尝试在连接条件中移动过滤条件,如下所示:

   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.Year=@year 
          and e.Month=@month
          and e.deptID=d.deptID)
   group by d.deptName
   order by d.deptName

答案 1 :(得分: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