不漂亮,但是这是一个原因,你不想违反第一范式和具有多值列...
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。
或者,如果你有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。
是有办法直接做,没有做那么多的工会?因为我确实有更多的,a +,b +,c +,d + ,那将是一个很重的查询。非常感谢!!!! – mongotop 2013-03-15 21:31:39
@Michael如果他的数据包含如示例 – 2013-03-15 22:51:42
中的空格,那么这将不起作用用'concat(','替换'concat(',',s.grade,',')'替换(s.grade,' ',''),',')'处理空格 – 2013-03-15 22:54:51