0

考虑这张表

student_name  grade
steve         a, b,d
mike          c,d,b
bob           a,d

我想写一个查询来提取我已经输出的等级数

a    2
b    2
c    1
d    3

我试过了:

select s1.grade, count(s1.grade) from student s1, student s2
where s1.grade = s2.grade
group by s1.grade

如何才能做到这一点?

4

2 回答 2

3

不漂亮,但这是你不想违反第一范式并拥有多值列的一个原因......

select 'a' as grade, count(*) as occurrences
from student
where grade like '%a%'

union all

select 'b' as grade, count(*) as occurrences
from student
where grade like '%b%'

union all

select 'c' as grade, count(*) as occurrences
from student
where grade like '%c%'

union all

select 'd' as grade, count(*) as occurrences
from student
where grade like '%d%'

在这里查看它的实际应用

或者,如果您有 gradesChris K 提出的表格,您可以执行以下操作:

select g.grade, count(s.student_name) as occurances
from 
  grades g
  left join student s
    on concat(',', s.grade, ',') like concat('%,', g.grade, ',%')
group by g.grade

在这里查看它的实际应用

于 2013-03-15T21:29:31.727 回答
2

或者,如果您有一个grades包含可能成绩列表的表格(称为 ):

grade
-----
a
b
c
d
e

那么下面的语句也可以工作:

select g.grade as [Grade], (select count(1) from student where grade like '%'+g.grade+'%') as [Count] from grades g order by g.grade asc

在将其他潜在成绩添加到计数中时,这可能会更加灵活。

但如上所述...避免正常化后果自负...

于 2013-03-15T21:38:11.947 回答