I am trying to append a column created by using COUNT(*) and GROUP BY to the original selection that was counted. However, the selection is pretty complex (much more than the WHERE ... line I’ve included in my example) so I’d rather not duplicate the code.
SQL Server doesn’t approve of my using an alias t1 inside of the left join statement. Any suggestions?
select t1.school, t1.grade,t1.individual,t2.cnt as 'class size' from (
select * from students
where (students.age < 16 and students.ACT_score is not null)
) as t1
left join (
select distinct school, grade, count(*) as 'cnt' from t1
group by school, grade
) as t2
on t1.school = t2.school and t1.grade = t2.grade
If it’s 2005 or newer, use a CTE: