我在编写SQL查询时有些生疏,我试图输出没有“ PA”的“联系人”列表
select a.first_name, a.last_name, (select count(b.contact_id)) as "PA Count"
from CRM_Contact a left join CRM_PA b on a.id = b.contact_id
where [PA Count] = 0
group by a.first_name, a.last_name
有人可以解释为什么我收到错误消息:
无效的列名“ PA Count”。
答案 0 :(得分:2)
如果您想COUNT
,则只需使用不带SELECT
语句的列名,并在HAVING
之后使用GROUP BY
语句:
select
a.first_name
, a.last_name
, Count(b.contact_id) as "PA Count"
from CRM_Contact a
left join CRM_PA b on a.id = b.contact_id
group by a.first_name, a.last_name
HAVING Count(b.contact_id) = 0
答案 1 :(得分:1)
WHERE
只能使用列或其别名。 PA Count
是一个聚合,它是在 WHERE
之后进行计算的。
过滤聚合是通过HAVING
子句进行的:
SELECT a.first_name,
a.last_name,
COUNT(b.contact_id) as [PA Count]
FROM CRM_Contact a
LEFT JOIN CRM_PA b ON a.id = b.contact_id
GROUP BY a.first_name,
a.last_name
HAVING Count(b.contact_id) =0
答案 2 :(得分:-1)
您忘记在以下查询中使用From
:
(select count(b.contact_id) from YourTable)