简体   繁体   中英

How to filter rows in SQL statement with aggregate function

I created a [Total Calls Made] column within the SQL, and don't know how to access it. I'm trying to ONLY show rows where [Total Calls Made] is equal to 0, but since it's not really a part of the table, I can't just add a clause that says where [Total Calls Made] = 0 . I attempted adding having count(distinct f.[id])=0 , but all that does is make the non-0 values in Total Call Made turn to Null. Why is that? What can I do to only select the 0 rows?

The SQL:

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 

Results:

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

Desired Result:

ID     First   Total Calls Made
--- |  ----  | ----------------
013 |  Joe   |        0

Using a join makes all non-0 values NOT display, which is the opposite of what I want.

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

Is that what you are after?

Try using a 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM