简体   繁体   中英

invalid expression error when using group by

I have two tables.

  • Employee table has two attributes. (employee_ID (PK), office_id)

  • Office table has two attributes. (office_id (PK), location) .

I need number of employees for each office.

So I wrote the following query.

SELECT COUNT(E.EMPLOYEE_ID), O.LOCATION
 FROM REALSTATE.EMPLOYEE AS E, REALSTATE.OFFICE AS O 
 WHERE E.OFFICE_ID=O.OFFICE_ID
 GROUP BY E.OFFICE_ID 

I get the following error. " Column reference 'O.LOCATION' is invalid, or is part of an invalid expression "

When you do a GROUP BY, everything in the SELECT must be either an aggregate or in the GROUP BY. Move the COUNT and OFFICE_ID to a subquery and JOIN them back to your main table.

You'll have to check the field names, it looks like you're not quite consistent on OFFICE vs OFFICE_ID in EMPLOYEE, but this should do it for you.

SELECT ECount, O.LOCATION
FROM (SELECT COUNT(E.EMPLOYEE_ID) as ECount, E.OFFICE
      FROM REALSTATE.EMPLOYEE AS E
      GROUP BY OFFICE) as C
INNER JOIN REALSTATE.OFFICE AS O on C.OFFICE=O.OFFICE_ID

The basic premise is you build an intermediate table (C) that has the office ID and how many people are in it, and join that back to OFFICE to resolve the name of the office associated with that ID

EDIT: @Gordon is correct, of course, MySQL does allow the non-standard behavior, sorry for the red herring. But try running the part inside the parenthesis alone and get it running, then put it back into the whole query and get that running, and when that all works you can pare it back down to the shorter notation.

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