表结构如下:
comment表
id user_id option1 option2 option3 option4
1   10      0       1        2          1
2   10      1       0        3          5
3   11      4       3        5          5如上user_id代表用户,这是个评论表,option1...option4代表评论分数(有4个选项打分)
要计算user_id=10这个用户的口碑值,公式:
(option1+option2+option3+option4)/4/2(2为user_id的记录数)如上计算出来是1.625,最后需要得到的结果是小数点保留一位(四舍五入)=1.6

解决方案 »

  1.   

    select user_id,
    cast(sum(option1+option2+option3+option4)/4.0/count(1) as dec(18,1))
    from comment
    where userid=10 --如果是求所有用户的平均值则把此条件去掉
    group by user_id
      

  2.   

    if object_id('[comment]') is not null drop table [comment]
    go
    create table [comment]([id] int,[user_id] int,[option1] int,[option2] int,[option3] int,[option4] int)
    insert [comment]
    select 1,10,0,1,2,1 union all
    select 2,10,1,0,3,5 union all
    select 3,11,4,3,5,5
    goselect user_id,
    平均值=cast(sum(option1+option2+option3+option4)/4.0/count(1) as dec(18,1))
    from comment
    --where user_id=10 --如果是求所有用户的平均值则把此条件去掉
    group by user_id/**
    user_id     平均值
    ----------- ---------------------------------------
    10          1.6
    11          4.3(2 行受影响)
    **/
      

  3.   

    cool,没想到count(1)来获取记录数,谢谢
      

  4.   


    SELECT     User_ID, CAST(SUM(Option1 + Option2 + Option3 + Option4) / 4.0 / COUNT(1) AS dec(18, 1)) AS kbz
    FROM         Comment
    WHERE     (User_ID = '10')
    GROUP BY User_ID如上语句提示错误:不能对decimal调用方法
      

  5.   

    SELECT     User_ID, CAST(SUM(Option1 + Option2 + Option3 + Option4) / 4.0 / COUNT(1) AS dec(18, 1)) AS kbz
    FROM         Comment
    WHERE     (User_ID = '10')
    GROUP BY User_ID/**
    User_ID     kbz
    ----------- ---------------------------------------
    10          1.6(1 行受影响)
    **/
    我这里显示是正确的,dec 你换成decimal或者numeric试试
      

  6.   

    decimal或者numeric都可以,结了