Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

How to resolve the error - must appear in the group by clause or be used in an aggregate function?

Asked by Amit Sinha Sep 30, 2022 5.3K views 1 answer
Share

About this question

I have two tables, an employee and phones. An employee can have 0 to n phone numbers. I want to list the employee names with their phone numbers. I am using the below query which runs fine.


SELECT empname,array_agg(phone number) AS phone numbers 

FROM employee LEFT OUTER JOIN phones ON employee.empid = phones.empid

GROUP BY employee.empid

The employee table might contain a large number of rows. I want to fetch only some employees at a time. For example I want to fetch 3 employees with their phone numbers. I am trying to run this query.

SELECT empname,array_agg(phone number) AS phone numbers 
FROM 
(SELECT * FROM employee ORDER BY empname LIMIT 3 OFFSET 0) AS employee 

LEFT OUTER JOIN phones ON employee.empid = phones.empid

GROUP BY employee.empid

But I get this error. ERROR:  column "employee.empname" must appear in the GROUP BY clause or be used in an aggregate function The only difference between two queries is that I am using subquery in the latter to limit the rows before joining. How do I solve this error?

Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.