选择多值列中重复值的时间

时间:2013-03-15 21:26:31

标签: mysql

考虑这个表

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

如何做到这一点?

2 个答案:

答案 0 :(得分: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%'

See it in action here

或者,如果你有像Chris K一样提出的grades表,你可以做类似以下的事情:

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

See it in action here

答案 1 :(得分: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

在增加其他潜在成绩方面,这可能会更加灵活。

但正如上面所说的那样......在你的危险中避免正常化......