2016-03-12 50 views
0

我已經看到類似的關於計數器和計算器限制的問題,但我還沒有完全能夠應用到這裏。我正在計算滿足特定條件的其他行的計數並顯示該計數。但是如果要顯示的最終計數是0,我不希望它顯示出來。只有當計算的計數大於0時才選擇一行

這裏是我的嘗試,使用具有:

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部分,喬的 「總來電」 顯示爲0。但是我怎麼能讓喬根本不露面呢?

+0

我刪除了MySQL的標籤。該語法看起來更像SQL Server。 –

回答

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; 
相關問題