2013-03-15 85 views
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 

如何才能做到這一點?

回答

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

或者,如果你有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

+0

是有辦法直接做,沒有做那麼多的工會?因爲我確實有更多的,a +,b +,c +,d + ,那將是一個很重的查詢。非常感謝!!!! – mongotop 2013-03-15 21:31:39

+0

@Michael如果他的數據包含如示例 – 2013-03-15 22:51:42

+0

中的空格,那麼這將不起作用用'concat(','替換'concat(',',s.grade,',')'替換(s.grade,' ',''),',')'處理空格 – 2013-03-15 22:54:51

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 

這也許是更靈活將其他潛在等級添加到計數中的條款。

但正如上面所說的......避開後果自負正常化......

+0

如果你還有類似'a +'和'a-'的成績,那麼你將不得不整理一些數據來獲得真正的值:搜索因爲像'%a%'一樣會包含'a +'和'a-'的計數 - 因此您需要從爲'a'返回的計數中減去這些計數 - 在給定數據的方式存儲。 – 2013-03-15 21:42:23

+0

+1用於提示「成績」表格。 – 2013-03-15 21:52:06