SQL查询:获取计数

时间:2013-02-27 16:26:16

标签: sql sql-server count

需要有关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

3 个答案:

答案 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个表来规范化表格,

  • ID(PK)
  • 名称

班级

  • ID(PK)
  • 名称

StudentClass

  • StudentID(FK)
  • ClassID(FK)

这是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+'%'