带GroupBy的T-SQL子查询

带GroupBy的T-SQL子查询,sql,sql-server,tsql,Sql,Sql Server,Tsql,我正在尝试对以下数据进行查询,这将告诉我每个学校有多少种类型的学校 所以对于旺斯沃思,我会 4 Secondary Schools 0 Foundation Schools 0 Community Schools 0 Primary Schools 0 Other 0 Academdy 2 Secondary School 1 Community School 2 Primary Schools 0 Other 0 Academdy 为了斯塔福德郡,我会的 4 Secondary Schoo

我正在尝试对以下数据进行查询,这将告诉我每个学校有多少种类型的学校

所以对于旺斯沃思,我会

4 Secondary Schools
0 Foundation Schools
0 Community Schools
0 Primary Schools
0 Other
0 Academdy
2 Secondary School
1 Community School
2 Primary Schools
0 Other
0 Academdy
为了斯塔福德郡,我会的

4 Secondary Schools
0 Foundation Schools
0 Community Schools
0 Primary Schools
0 Other
0 Academdy
2 Secondary School
1 Community School
2 Primary Schools
0 Other
0 Academdy
到目前为止,我得到的是这个,但它没有生成正确的数字,并且包含重复的学校lea

有人能告诉我我遗漏了什么吗

谢谢

select school_lea,
(select count(s.school_id)  from school inner join school s on s1.school_id = s.school_id where (s.[type] = 'Secondary School')  ) as noofSecondary,
(select count(s.school_id)  from school inner join school s on s1.school_id = s.school_id where (s.[type] = 'Nursery/Pre-School')  ) as noooPrimarys
from school s1
Group by school_lea, school_id
资料


在CASE的帮助下,您可以这样做:

select
    school_lea,
    sum(case type when 'Secondary School' then 1 end) noofSecondary,
    *(the rest of your types)*
from myTable
group by
    school_lea

1在SELECT and use normal JOIN中删除子查询2首先准备数据,例如使用CTE,然后按CLOSE分组,您要按学校分组。事实上,你已经按照一个唯一的id进行分组…Thx,是的,就是这样@马特贝利