SQL查询中的列名无效

时间:2019-03-07 10:53:38

标签: sql-server

我在编写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”。

3 个答案:

答案 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)