calculate average rating in sql server

前端 未结 3 895
耶瑟儿~
耶瑟儿~ 2021-01-14 17:52

this is my table:

\"enter

I want to fetch records of Those Vendor which contai

3条回答
  •  北海茫月
    2021-01-14 18:48

    Many users have used the AVERAGE function to calculate the average of a series of data. But what do you do when you have summary data instead of individual responses and need to calculate an average? (For example, counts of the number of people who selected each rating on a 5-point rating scale like the rating of a product.)

    How to Calculate a Weighted Average

    Let’s say you want to get the average overall rating for each product:

    • For rating 1, (9) nine people.
    • For rating 2, (13) Thirteen people.
    • For rating 3, (1) one people.

    Using the AVERAGE function would result in an average of 7.7. Of course, this doesn’t make any sense. We should expect an average within the range of the scale (1 to 5).

    In order to correctly calculate the average overall response to each question, we need to:

    1. Multiply the number of individuals selecting each rating by the corresponding rating value (1 – 5)
    2. Add the results of those calculations together.
    3. Divide that result by the total number of responses to the question.

    Example:

        SELECT
        SUM(
        case 
            WHEN FLOOR(rating) = 1 THEN rating
            WHEN FLOOR(rating) = 2 THEN rating *2
            WHEN FLOOR(rating) = 3 THEN rating *3
            WHEN FLOOR(rating) = 4 THEN rating *4
            WHEN FLOOR(rating) = 5 THEN rating *5        
        end    
        ) / SUM(rating)
        FROM tableRatings
    

提交回复
热议问题