Considering
Table a
Id INTEGER Name VARCHAR(50)
Table B
Id INTEGER FkId INTEGER ; Foreign key to Table A
I want to count the values โโof each FkId value:
SELECT FkId, COUNT(FkId) FROM B GROUP BY FkId
Now I just want to also output the name from Table A
This will not work:
SELECT FkId, COUNT(FkId), a.Name FROM B b INNER JOIN A a ON a.Id=b.FkId GROUP BY FkId
because a.Name not contained in the GROUP BY (it throws an error is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause ).
The goal is to move from a conclusion like this
FkId Count 1 42 2 25
for output as follows
FkId Count Name 1 42 Ronald 2 22 John
There are many coincidences for SO for this error message, but some, for example, https://stackoverflow.com/a/312960/ ... have comments such as โwill generate 3 scan tables, not 1, so it will not scale.โ
How can I effectively include a field from a merged Table B (which has a 1: 1 FkId to FkId ) in the query output?
sql sql-server aggregate-functions
Eric J.
source share