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

きれいではありませんが、これが、第一正規形に違反したくない理由の1つであり、複数値の列があります...

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 に答える