使用count连接两个表,其中不返回计数为0的行

时间:2012-11-11 18:30:14

标签: sql-server sql-server-2012

我有一个SQL问题。我的查询如下:

Select 
    s.idseminar, count(p.seminar)
From 
    Seminar as s 
LEFT OUTER JOIN 
    Predbiljezba AS p ON p.seminar = s.idSeminar 
WHERE 
    p.obradjena = 1
Group by 
    s.idSeminar


idseminar: 1, 2
count....: 2, 2

它应显示课程(研讨会)的已接受申请的数量(predbiljezbaobradjena = 1< ==已接受状态)。它几乎完成了我的需要。

我想要的是它显示所有课程,即使接受的订阅数为0.如果我省略where子句:

Select 
    s.idseminar, count(p.seminar)
From 
    Seminar as s 
LEFT OUTER JOIN 
    Predbiljezba AS p ON p.seminar = s.idSeminar
Group by 
    s.idSeminar


idSeminar: 1,2,3,4       
count....: 2,2,1,0

它显示所有课程,即使它有0个应用程序,但在这些应用程序中有一些未处理或被拒绝,我不希望它们在我的查询中弹出。我找到了这个链接

Displaying rows in SQL Server where COUNT = 0

但那里的解决方案似乎没有用。我正在使用SQL Server 2012.

2 个答案:

答案 0 :(得分:1)

将条件移至LEFT JOIN

Select s.idseminar, count(p.seminar)
From Seminar as s
LEFT OUTER JOIN Predbiljezba AS p ON p.seminar = s.idSeminar AND p.obradjena = 1
Group by s.idSeminar

答案 1 :(得分:0)

您可以在主要选择条款

中使用subselect
Select s.idseminar, 
   (select count(p.seminar) 
   from Predbiljezba p
   where p.seminar = s.idSeminar and p.obradjena = 1) as seminarCount
from Seminar s