I had a similar query and a similar issue.
SELECT
*
FROM
Users ru
LEFT OUTER JOIN
(
SELECT ru1.UserID, COUNT(*)
FROM Referral r
LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
GROUP BY ru1.UserID
) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID
I found that SQL Server was choking on the COUNT(*)
column, and was giving me the error No column was specified for column 2.
Putting an alias on the COUNT(*)
column fixed the issue.
SELECT
*
FROM
Users ru
LEFT OUTER JOIN
(
SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
FROM Referral r
LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
GROUP BY ru1.UserID
) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID