Your original query was correct, with a slight change:
SELECT MemberID, MemberName, (SELECT COUNT(MemberID) FROM table WHERE MemberID = M.MemberID GROUP BY MemberID) AS MemberCount
FROM table M
WHERE M.MemberRole = 'E'
Question
I want to do a nested aggregation, is this possible? SQL Server 2012 is returning an error when I try to do the following:
SELECT SUM(COUNT(memberID)) FROM table
The situation I have is the following: I have members who have the same member ids as their dependents in the same table. I want to get the count of the the members and their dependents based on the memberID, however, I want the count in a column next to the main enrollee which is identified by another column as an e.
SELECT memberID, memberName, COUNT(memberID)
FROM table
WHERE memberRole = 'e'
The above would return 1 for all results, so I was thinking if I count the memberIds, then sum them would work but that returned an error, Am I doing something wrong? What is the best way to reach this porblem
Solution
Your original query was correct, with a slight change:
SELECT MemberID, MemberName, (SELECT COUNT(MemberID) FROM table WHERE MemberID = M.MemberID GROUP BY MemberID) AS MemberCount
FROM table M
WHERE M.MemberRole = 'E'
OTHER TIPS
try this:
SELECT memberID, memberName, Sum(CNT) From
(
SELECT memberID, memberName, COUNT(memberID) CNt
FROM table
WHERE memberRole = 'e'
) t
group by memberID, memberName