HAVING中的列名无效

时间:2018-05-21 16:22:57

标签: sql sql-server

任何人都知道为什么“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'。

3 个答案:

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

在逻辑查询处理SELECTHAVINGWHERE子句后执行。因此,它无法识别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