日期:2014-05-17  浏览次数:20389 次

对评价内容的简单统计
本帖最后由 zyxlsh 于 2013-04-29 15:59:27 编辑
有个调查试卷,共有5个问题
用户可以选择对其中的几项进行评价。表格设计时,字段有:
用户名:username varchar(20)
时间:sj datetime
评价值1:pj1 int
评价值2:pj2 int
评价值3:pj3 int
评价值4:pj4 int
评价值5:pj5 int

当用户没有选择对某项评价时,值为0;如果有评价,则分值在50 - 100之间。
我现在有如下记录:
username           sj        pj1  pj2  pj3  pj4  pj5 
user1    2013-1-1 11:11:11  100   0    100  0    60
user1    2013-2-1 12:11:11  80    55   50   0    50
user1    2012-1-1 20:11:10  90    77   0    90   70
user2    2012-5-1 05:11:10  70    80   60   0    60

对这三条记录统计后的结果,
对用户user1  pj1平均值(100+80+90)/3=90   3为有效的评价次数
             pj2平均值(55+77)/2=66
             pj3平均值(100+50)/2=75
             pj4平均值(90)/1=90
             pj5平均值(60+50+70)/3=60
对用户user2 只有一条记录

统计后的结果如下:
user1   90  60  75  90  60
user2   70  80  60  0   60

这个如何实现啊?
分类统计

------解决方案--------------------

declare @t table (
  username varchar(30),
  sj datetime,
  pj1 int,
  pj2 int,
  pj3 int,
  pj4 int,
  pj5 int
)

insert into @t 
select 'user1','2013-1-1 11:11:11',100 ,0,100,0,60 union all
select 'user1','2013-2-1 12:11:11',80,55,50,0,50 union all
select 'user1','2012-1-1 20:11:10',90,77,0,90,70 union all
select 'user2','2012-5-1 05:11:10',70,80,60,0,60

select username,
       case when cnt_1>0 then total_1/cnt_1 else 0 end pj1,
       case when cnt_2>0 then total_2/cnt_2 else 0 end pj2,
   case when cnt_3>0 then total_3/cnt_3 else 0 end pj3,
   case when cnt_4>0 then total_4/cnt_4 else 0 end pj4,
   case when cnt_5>0 then total_5/cnt_5 else 0 end pj5
from (
select username,
   sum(pj1) total_1,sum(case pj1 when 0 then 0 else 1 end) cnt_1,
   sum(pj2) total_2,sum(case pj2 when 0 then 0 else 1 end) cnt_2,
   sum(pj3) total_3,sum(case pj3 when 0 then 0 else 1 en