mysql显示所有行的平均值

时间:2016-12-09 18:35:04

标签: php mysql math average rating

表格结构

rating.post_id
rating.user_id
rating.rate_like
rating.rate_dislike

示例数据:

rating.post_id = 1
rating.user_id = 1
rating.rate_like = 1
rating.rate_dislike = 0

rating.post_id = 1
rating.user_id = 2
rating.rate_like = 1
rating.rate_dislike = 0

rating.post_id = 1
rating.user_id = 3
rating.rate_like = 0
rating.rate_dislike = 1

鉴于上述结构,帖子1由用户1,2和3评级,其中用户1和2投票赞成用户3投票不喜欢。

有了这个,如何得到评级为五(5)星评级的平均值?

式: (((total rate_like / total votes) * 100) * 0.5) / 10 = Rate (round to nearest .5)

实施例: (((2/3) * 100) * 0.5) / 10 = 3.33 (round to 3.5)

评分为3.5分,满分5分

预期的mysql输出将是:

post_id = 1
rate_like = 2
rate_dislike = 1
total_rating = 3.5

这是我对sql所做的事情,但我不知道如何只将它变成一个sql语句。

这得到了平均值:

select round(round((((sum(rate_like) / (sum(rate_like) + sum(rate_dislike)) * 100) * 0.5) / 10) * 2) / 2, 1) from rating group by post_id

其中应合并到此声明中:

SELECT post_id, sum(rate_like), sum(rate_dislike), (sum(rate_like) + sum(rate_dislike)) from rating group by post_id

合并这两个语句会出现subquery returns more than 1 row错误:

SELECT post_id, sum(rate_like), sum(rate_dislike), (sum(rate_like) + sum(rate_dislike)), (select round(round((((sum(rate_like) / (sum(rate_like) + sum(rate_dislike)) * 100) * 0.5) / 10) * 2) / 2, 1) from rating group by post_id) from rating group by post_id

where个语句中添加select子句可以解决问题,但需要显示多行。

1 个答案:

答案 0 :(得分:0)

没关系......能够解决这个问题。子查询用作连接表而不是列。

SELECT rating.post_id, sum(rate_like), sum(rate_dislike), (sum(rate_like) + sum(rate_dislike)), column_rating from rating inner join ( select post_id, round(round((((sum(rate_like) / (sum(rate_like) + sum(rate_dislike)) * 100) * 0.5) / 10) * 2) / 2, 1) as column_rating from rating group by post_id ) as rating_table on rating.post_id = rating_table.post_id group by rating.post_id