任何人都知道为什么“CoID”值无法识别?
select
ac.AccountID
, max(case when c.Name = 'email' then c.Data end) as Email
, max(case when c.Name = 'phone' then c.Data end) as Phone
, max(a.CompanyID) as CoID
from paul_AccountContacts ac
left join paul_Contact c on c.ID = ac.ContactID
left join paul_Account a on a.ID = ac.AccountID
having (CoID in (1506)) --ERROR HERE
order by ac.AccountID
错误:
无效的列名称'CoID'。
答案 0 :(得分:2)
如果您要过滤单个记录,请使用where
子句代替having
select
ac.AccountID,
max(case when c.Name = 'email' then c.Data end) as Email,
max(case when c.Name = 'phone' then c.Data end) as Phone,
max(a.CompanyID) as CoID
from paul_AccountContacts ac
left join paul_Contact c on c.ID = ac.ContactID
left join paul_Account a on a.ID = ac.AccountID
group by ac.AccountID
where a.CompanyID = 1506 -- use IN clause whenever you have multiple CompanyID ids
order by ac.AccountID
但是,如果您希望在某些聚合之后过滤掉或基于聚合过滤掉或使用聚合},则使用having
em>
因此。您的查询将与having
子句一样:
select
ac.AccountID,
max(case when c.Name = 'email' then c.Data end) as Email,
max(case when c.Name = 'phone' then c.Data end) as Phone,
max(a.CompanyID) as CoID
from paul_AccountContacts ac
left join paul_Contact c on c.ID = ac.ContactID
left join paul_Account a on a.ID = ac.AccountID
group by ac.AccountID
having max(a.CompanyID) = 1506
order by ac.AccountID;
答案 1 :(得分:1)
在逻辑查询处理SELECT
在HAVING
或WHERE
子句后执行。因此,它无法识别SELECT
中创建的列名称。请尝试使用max(a.CompanyID)
:
select
ac.AccountID
, max(case when c.Name = 'email' then c.Data end) as Email
, max(case when c.Name = 'phone' then c.Data end) as Phone
, max(a.CompanyID) as CoID
from paul_AccountContacts ac
left join paul_Contact c on c.ID = ac.ContactID
left join paul_Account a on a.ID = ac.AccountID
Group by ac.AccountID
having max(a.CompanyID) = 1506 --ERROR HERE
order by ac.AccountID
答案 2 :(得分:0)
您缺少group by子句,您显然想要使用聚合函数。我假设您选择的是:
group by ac.AccountID
之后,您是否只尝试使用1506的CompanyID,或者您只想显示最大值为1506的分组结果:第一个是这样的:
Where a.CompanyID = 1506
第二个像这样
having max(a.CompanyID)=1506