SQL QUERY-多个COUNT返回错误(相同)的结果

时间:2016-05-12 11:20:45

标签: sql sql-server sql-server-2008

如何在不给我相同输出的情况下组合这两个查询?

第一个查询是:

select   vwemployee.directorateName   , count(vwemployeeCourse.employeeId) as t1 

from vwemployee , vwemployeeCourse 

where  vwemployee.directorateName = vwemployeeCourse.directorateName 

GROUP BY vwemployee.directorateName

这是第二个查询:

select vwemployee.directorateName , count(vwemployee.directorateName) as t2 

from vwemployee , employeeCourse

where vwemployee.Id = employeeCourse.employeeId 

GROUP BY  vwemployee.directorateName

我将使用合并查询生成报告

第一栏是董事会的名称

顺便说一句,当我把它们结合起来时,我的自我t1和t2有相同的结果但是当它们分开时它给了我正确的结果

  

t1列应该显示这个具体的课程数量   董事会采取,t2栏应显示有多少员工   在这个理事会下学了这门课程

     

因此,合并查询的表格总列数应为3列

3 个答案:

答案 0 :(得分:0)

您可以使用SUM(IF())

SELECT vwemployee.directorateName, 
    SUM(IF(vwemployee.directorateName = vwemployeeCourse.directorateName),1,0) directorateCount,
    SUM(IF(vwemployee.Id = employeeCourse.employeeId),1,0) idCount,
    FROM vwemployee , vwemployeeCourse 
    WHERE  vwemployee.directorateName = vwemployeeCourse.directorateName 
        OR vwemployee.Id = employeeCourse.employeeId
    GROUP BY vwemployee.directorateName

注意:我没有测试它,所以可能需要一些工作。

答案 1 :(得分:0)

使用以下查询。

 Select max(vwemployee.directorateName), sum(t1) as t1, sum(t2) as t2
(select vwemployee.directorateName , 0 as t1 ,count(vwemployee.directorateName) as t2
UNION 
select vwemployee.directorateName,count(vwemployeeCourse.employeeId) as t1 , 0 AS t2)

答案 2 :(得分:0)

尝试以下查询:

CATextLayer

我重新格式化了您的查询,以使用ANSI-Joins

替换旧样式连接语法