简体   繁体   English

Postgres SQL:如何在更改平均值的现有值后重新计算平均值

[英]Postgres SQL : how do I recalculate average value, after an existing value from the average has been changed

Using the function below, when you first rate a title, and then afterwards give a different rating for the title the averagerating for that title will be incorrect.使用下面的函数,当您第一次对标题进行评分,然后为该标题给出不同的评分时,该标题的平均评分将是不正确的。

The number of votes for title 'tt9910206' is 4, and averagerating is 8 before the function is called.标题 'tt9910206' 的投票数为 4,在调用该函数之前平均为 8。 When calling the function the first time, and giving a rating of 7, the numvotes is 5 and the expected average is 7,8, which the function does return.第一次调用该函数并给出 7 分时,numvotes 为 5,预期平均值为 7,8,该函数确实返回该值。 But when changing the rating from 7 to 8 the expected result is 8, yet the function returns 7,84.但是当将评分从 7 更改为 8 时,预期结果为 8,但函数返回 7,84。

I suspect it's because the function doesnt take into account that the user has undone their rating, when recalculating the average.我怀疑这是因为在重新计算平均值时,该函数没有考虑到用户已经取消了他们的评分。 How do I fix this, so when a user changes their rating, the function recalculates the average by using the averagerating number from before a user gave it a rating in the first place?我该如何解决这个问题,所以当用户更改他们的评分时,该函数会使用用户最初给它评分之前的平均评分数来重新计算平均值?

Edit: Found the answer here编辑:在这里找到答案

Finding an average after replacing a current value 替换当前值后求平均值

You may have other issues in your function.您的函数中可能还有其他问题。 But you seem to be forgetting that Postgres does integer division.但是您似乎忘记了 Postgres 进行整数除法。 So, 1/2 is 0 , not 0.5 .所以, 1/20 ,而不是0.5

I notice calculations like this:我注意到这样的计算:

count( user_titlerate.tconst ) / count( user_titlerate.tconst ) 

COUNT() returns and integer. COUNT()返回整数。 I usually modify this to:我通常将其修改为:

count( user_titlerate.tconst ) * 1.0 / count( user_titlerate.tconst ) 

But you can use other constructs such as:但是您可以使用其他结构,例如:

count( user_titlerate.tconst )::numeric / count( user_titlerate.tconst ) 

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

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