I have a parent table A(id,fld1,fld2), and child table B(id,parentId,fld1, fld2)
I want to select A.* and the count of the children rows
my query is:
SELECT A.*, COUNT(B.parentId)
INNER JOIN A ON B.parentId = A.id
GROUP BY B.parentId
but I'm getting:
Column 'A.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Here's another way:
SELECT A.*, B.cnt
FROM A
CROSS APPLY (SELECT COUNT(*) As cnt
FROM B
WHERE B.parentId = A.id
) As B
Old fashion (correlated subquery):
SELECT A.*, (SELECT COUNT(*) As cnt
FROM B
B.parentId = A.id
) As cnt
FROM A
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.