简体   繁体   中英

Aggregate function error in SQL Server 2008 R2

I want to retrieve the empId that belongs to more than one city. So I use this query:

select empId 
from phone 
group by city 
having  count(city) > 1

but I get an error:

Msg 8120, Level 16, State 1, Line 1
Column 'phone.empId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Use GROUP BY and HAVING count distinct city to find empId's with more than 1 city:

SELECT empId
FROM phone
GROUP BY empId
HAVING COUNT(DISTINCT city) > 1

该错误的意思是,如果您要使用GROUP BY子句,那么在SELECT语句中,您只能“选择”要分组的列并在该列上使用聚合函数,因为其他列将不会出现在结果表中。

You can use ROW_NUMBER() also to work it :
following code should work :

select empId from 
(
select distinct empId,city,ROW_NUMBER() over(partition by empId order by city) rn
 from phone 
 ) a
 where rn>1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM