无法在表达式中使用聚合或子查询

问题描述 投票:0回答:2

我正在尝试将行和占用代码显示为列和行内的dcode计数,但它给出了一个错误:

无法在GROUP BY子句列表中使用的表达式中使用聚合或子查询。

select count(*) as total

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='49' and left(zip,3) between '900' and '934') as 'Doctors-49'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='17' and left(zip,3) between '900' and '934') as 'Health Services-17'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='53' and left(zip,3) between '900' and '934') as '53=Insurance/Underwriters'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='41' and left(zip,3) between '900' and '934') as '41=Occupational Therapy' 

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='48' and left(zip,3) between '900' and '934') as '48=Nurses'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='43' and left(zip,3) between '900' and '934') as '43=Psychologists'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='21' and left(zip,3) between '900' and '934') as '21=Teacher/Educator'

from c122117a_A o
group by count(*) 
order by count(*) 
sql sql-server
2个回答
1
投票

尝试这样的事情,完成省略的列

select count(o.dcode) as total
,sum(case when occupation='49' and left(zip,3) between '900' and '934' then 1 else 0 end) as 'Doctors-49'
,sum(case when occupation='17' and left(zip,3) between '900' and '934' then 1 else 0 end) as 'Health Services-17'
...
from c122117a_A o
group by o.dcode 

0
投票

group by count(*)替换group by dcode。因为您在子查询中引用了o.dcode,所以必须指定哪一个。如果你不按它们分组,所有的dcode都会被放在一起,数据库无法确定使用哪一个(值)。

© www.soinside.com 2019 - 2024. All rights reserved.