【问题标题】:Right Outer join issue右外连接问题
【发布时间】:2012-11-07 00:03:42
【问题描述】:

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

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

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

【问题讨论】:

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


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

    【讨论】:

      【解决方案2】:

      我认为您需要像这样更改代码

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 2014-02-24
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        相关资源
        最近更新 更多