简体   繁体   中英

How do you calculate using sum in SQL Server

I am trying something like this:

select sum(R_Value) ,((5/cast(sum(R_Value) as int)) * 100.000000000) 
from R_Rating 
where R_B_Id = 135

But I keep getting value 0, sum(R_Value) = 6, so I just want a percentage out of (5/sum(R_Value)) * 100.

How can I get this?

I have a rating of 5 so each user has a rating they can make select from 1 to 5, so what i need is a formula that takes in the sum and takes into account how many users have rated and give us a result from 1 to 5 in the end

Something like this may work but i need to round up to one decimal place to get a whole number.

select sum(R_Value), ((count(*)/cast(sum(R_Value) as float)) * 10) 
from R_Rating 
where R_B_Id = 135

I recommend writing this as:

select sum(R_Value) ,
      (500.0 / sum(R_Value))
from R_Rating 
where R_B_Id = 135;

This avoids an integer division.

To get the average rating you need to force floating point algebra. For example:

select 1.0 * sum(R_Value) / count(*)
from R_Rating 
where R_B_Id = 135

Then, if your query selects three rows with the values: 1 , 4 , and 5 , then this query will return 3.33 stars as the average. That is:

= 1.0 * (1 + 4 + 5) / 3
= 1.0 * 10 / 3
= 10.0 / 3
= 3.33333333

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