2013-03-15 99 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