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

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

4

2 回答 2

1

When you apply the filter condition through where clause after join, it filters out all the records which doesn't satisfy the filter criteria. Try moving your filter criteria in join condition itself as below:

   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
于 2012-11-19T04:07:21.357 回答
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 Fiddle 查询:http ://sqlfiddle.com/#!3/b1105/17

于 2012-11-19T04:30:02.287 回答