如何使用聚合函数过滤 SQL 语句中的行
How to filter rows in SQL statement with aggregate function
我在 SQL 中创建了一个 [Total Calls Made] 列,但不知道如何访问它。我试图只显示 [Total Calls Made] 等于 0 的行,但由于它实际上不是 table 的一部分,我不能只添加一个说 where [Total Calls Made] = 0
的子句。我尝试添加 having count(distinct f.[id])=0
,但所做的只是使 Total Call Made 中的非 0 值变为 Null。这是为什么?我只能对 select 0 行做什么?
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
结果:
ID First Total Calls Made
--- | ---- | ----------------
011 | Bob | 4
012 | Susan | 2
013 | Joe | Null
期望的结果:
ID First Total Calls Made
--- | ---- | ----------------
013 | Joe | 0
使用连接使所有非 0 值不显示,这与我想要的相反。
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
这就是你想要的吗?
尝试使用 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
我在 SQL 中创建了一个 [Total Calls Made] 列,但不知道如何访问它。我试图只显示 [Total Calls Made] 等于 0 的行,但由于它实际上不是 table 的一部分,我不能只添加一个说 where [Total Calls Made] = 0
的子句。我尝试添加 having count(distinct f.[id])=0
,但所做的只是使 Total Call Made 中的非 0 值变为 Null。这是为什么?我只能对 select 0 行做什么?
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
结果:
ID First Total Calls Made
--- | ---- | ----------------
011 | Bob | 4
012 | Susan | 2
013 | Joe | Null
期望的结果:
ID First Total Calls Made
--- | ---- | ----------------
013 | Joe | 0
使用连接使所有非 0 值不显示,这与我想要的相反。
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
这就是你想要的吗?
尝试使用 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