I have a simple SQL Server 2008 database with two tables like this:
TableA:
(PK)"ID"
"Field"
and
TableB:
(PK)"ID"
(FK)"ID_TableA"
"Field"
I want to select all the fields in TableA
and also how many corresponding rows in TableB
there are for every TableA
row:
SELECT A.*,
COUNT(B."ID") as "B's number"
FROM "TableA" A
LEFT JOIN "TableB" B ON (A."ID" = B."ID_TableA")
GROUP BY A."ID", A."Field"
This works well, but I have this issue: if TableA
is further modified (let's say we have to add another Field2
column) I have to update the SELECT
statement above to include that field in the GROUP BY
clause. Otherwise I receive this error when executing the operation:
"Column 'TableA.Field2' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
Is there a way to avoid this so I can modify my TableA
without also updating all the statement like the one above?