如何使用聚合函数筛选SQL语句中的行

时间:2016-03-14 18:22:18

标签: sql sql-server group-by aggregate-functions sql-function

我在SQL中创建了[Total Calls Made]列,并且不知道如何访问它。我试图仅显示[Total Calls Made]等于0的行,但由于它不是表的一部分,我不能只添加一个说{{ 1}}。我尝试添加where [Total Calls Made] = 0,但所有这一切都是使Total Call Made中的非0值变为Null。这是为什么?我该怎么办才能选择0行?

SQL:

having count(distinct f.[id])=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

使用连接会使所有非0值都不显示,这与我想要的相反。

2 个答案:

答案 0 :(得分:1)

SELECT p.[Ref] as [ID], p.[First] as [First], Count(f.[Field]) as CallsMade 
from [person] p 
left outer join [field] f on f.[Related] = p.[Ref] and f.[Field] = 'person_that_called'
group by p.[Ref], p.[First]
having Count(f.[Field]) =0

这就是你追求的目标吗?

答案 1 :(得分:0)

尝试使用cte

WITH    cte
      AS (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
         )
SELECT  [ID]
       ,[First]
       ,ISNULL([Total Calls Made],0) as [Total Calls Made]
FROM    cte
WHERE   ISNULL(cte.[Total Calls Made],0) = 0