需要有关MS SQL查询的建议:
表:学生id name class
-- ---- -----
1 John Math, Biology
2 Jane English
3 Mark Math
table:class
id name
-- ----
1 Math
2 English
3 Biology
4 History
期望的输出
name count
---- -----
Math 2
English 1
Biology 1
History 0
答案 0 :(得分:2)
<击> 撞击>
<击>这适用于MySQL
。
SELECT a.name, COUNT(b.id) as `totalCount`
FROM class a
LEFT JOIN students b
ON FIND_IN_SET(a.name, b.class) > 0
GROUP BY a.name
击> <击> 撞击>
为了获得最佳性能,请通过创建3个表来规范化表格,
生
班级
StudentClass
这是many-to-many
关系,因为学生可能有很多课程,而课程也有很多学生。
查询应如下所示,
SELECT a.Name, COUNT(b.ClassID) totalCount
FROM Class a
LEFT JOIN StudentClass b
ON a.id = b.ClassID
GROUP BY a.Name
答案 1 :(得分:1)
以下是SQL Server的答案:
SELECT c.name, COUNT(b.id) as `totalCount`
FROM class c LEFT JOIN
students s
ON ','+s.class+',' like '%,'+a.name+',%'
GROUP BY c.name
实际上,这对于您在类名中拥有的空格并不适用。请尝试使用此on
:
ON ','+replace(s.class, ' ', '')+',' like '%,'+replace(a.name, ' ', '')+',%'
答案 2 :(得分:1)
select
class.name as name,
count(*) as count
from students, class
where students.class like '%'+class.name+'%'