仅在计算的计数大于0时选择行

时间:2016-03-12 00:16:44

标签: sql

我已经看到有关stackoverflow的计数和限制的类似问题,但我还没有完全能够在这里应用它。我正在计算满足特定条件的其他行的计数并显示该计数。但如果要显示的最终计数为0,我不希望它显示出来。

这是我尝试过的,使用HAVING:

select p.[ref] as [ID],
p.[first] as [First],

(select count(distinct f.[id]) from [field] f 
where (f.[related] = p.[id]) and (f.[field] = 'person_that_called') 
having count(distinct f.[id])>0) as [Total Calls Made]

from [person] p 

但这导致显示如下:

ID     First   Total Calls Made
--- |  ----  | ----------------
011 |  Bob   |       4
012 |  Susan |       2
013 |  Joe   |      Null

如果没有HAVING部分,Joe的“Total Calls”会显示为0.但是我怎么能让Joe完全不显示?

1 个答案:

答案 0 :(得分:1)

使用join

select p.[ref] as [ID], p.[first] as [First], f.[Total Calls Made]
from [person] p join
     (select f.[related], count(distinct f.[id]) as [Total Calls Made]
      from [field] f 
      where f.[field] = 'person_that_called'
      group by f.[related]
     ) f
     on f.related = p.id
where [Total Calls Made] > 0;