简体   繁体   中英

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. 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. But when changing the rating from 7 to 8 the expected result is 8, yet the function returns 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. So, 1/2 is 0 , not 0.5 .

I notice calculations like this:

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

COUNT() returns and integer. 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 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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