不漂亮,但是這是一個原因,你不想違反第一範式和具有多值列...
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