简体   繁体   English

mysql显示所有行的平均值

[英]mysql display calculated average for all rows

Table structure 表结构

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

Sample data: 样本数据:

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

Given the structure above, post 1 is rated by user 1, 2 and 3 wherein users 1 and 2 voted for like while user 3 voted for dislike. 鉴于上述结构,帖子1由用户1,2和3评级,其中用户1和2投票赞成用户3投票不喜欢。

With that, how to get the average where rating is a five(5) star rating? 有了这个,如何获得评级为五(5)星评级的平均值?

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

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

Rate would be 3.5 out of 5 stars 房价将是3.5星,最高为5星

Expected mysql output would be: 预期的mysql输出将是:

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

Here's what I've done with the sql but I have no idea how to make it into one sql statement only. 这是我用sql做的,但我不知道如何只将它变成一个sql语句。

This gets the average: 这得到了平均值:

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

In which should be merge into this statement: 其中应合并到此声明中:

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

Merging the two statements gives an error of subquery returns more than 1 row : 合并这两个语句会导致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

Adding a where clause on both select statements solves the issue but it is needed to display multiple rows instead. 在两个select语句上添加where子句可以解决问题,但需要显示多行。

Nevermind... was able to figure this out. 没关系......能够解决这个问题。 Subquery is used as a joined table instead of a column. 子查询用作连接表而不是列。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM