Sql 右外连接问题
我有两个表要联接并从中筛选数据。我使用了一个存储过程来实现这一点。我的目的是将第二个表(即部门)中的每个项目都带到第一个表(即员工)中,即使它们没有匹配的记录,最后显示计数。以下是我使用的代码片段:Sql 右外连接问题,sql,sql-server-2008,stored-procedures,join,outer-join,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.deptI
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
但是,它没有显示我想要的,也没有找出真正的问题 当您通过
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
我想你需要像这样修改代码
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 FIDLE: