一道mysql分组统计问题

Posted on 2009-06-03 14:42 飘摇 阅读(1211) 评论(0)  编辑  收藏 所属分类: 数据库
 试题要求:
  

有一个表   Table   Test   结构如下   :
  姓名         颜色1         颜色2             评语  
  name       color1         color2         commint  
  a                 1                   -1                   好  
  b                 2                     1                 不好  
  a                 3                     2                 一般  
  c                 2                     1                   ss  
  a               -1                     2                   aa  
  b                 4                     -1                 bb  
  a                 2                     -1                   cc  
  按照如下规则进行统计:  
  按姓名分组求平均值,如果值为-1就不统计,评语累计  

  统计后结果如下:  
  name       color1         color2         commint  
  a               2                       2                   好,一般,aa,cc  
  b               3                       1                 不好,bb  
  c               2                       1                     ss
-----------------------------------------------------------------------------------------------------------------------------------------------------
分析表结构和规则,可以得到如下信息:
首先按name 分组(group by **),计算两列的平均值(想到的函数avg()),去除值为-1的列,合并相同列的字段值(想到 group_concat(name)),
 但是写时候avg()不可以,有条件应该想到 case when then else end来进行判断,
 计算平均值可以这样算:用分子/分母的方法,
 分子:所有列的和如果为-1则为0 sum(case color1 when -1 then 0 else color1 end)
 分母:所有的列数和,如果为-1则为0,反之为1 sum(case color1 when -1 then 0 else 1 end),
这有点像加权平均数,
  select  name ,sum(case color1 when -1 then 0 else color1 end)/sum(case color1 when -1 then 0 else 1 end) as color1,
                      sum(case color2 when -1 then 0 else color2 end )/sum(case color2 when -1 then 0 else 1 end ) as color2,
                     group_concat(commint) from Test group by name;
-----------------------------------------------------------------------------------------------------------------
group_concat()用法小结:
  group_concate(name)  对该列进行合并
  group_concate(distinct name) 去除重复元素
  group_concate( name separator ':')按separator ':' :格式进行分割


只有注册用户登录后才能发表评论。


网站导航:
 

posts - 15, comments - 3, trackbacks - 0, articles - 2

Copyright © 飘摇