I have the following tables
CREATE TABLE Foos (
[Id] INT IDENTITY,
-- Other fields
)
CREATE TABLE Boos (
[Id] INT IDENTITY,
[FooId] INT,
-- Other fields
)
I am trying to execute a very simple query:
SELECT f.Id, COUNT(*)
FROM Foos f
JOIN Boos b on f.Id = b.FooId
GROUP BY b.FooId
Obviously I am getting an error because of the GROUP BY. The error message is
Column 'Foo.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
When I change the group by to GROUP BY f.Id everything works fine again.
My question is, why would SQL Server throw that error while it already knows for sure that f.Id = b.FooId from the join, that Foo.Id is unique from the IDENTITY, and that the grouping will logically return the same count due to the join on a primary key?