Sql-server – What does numeric operations mean in a sum in sql expression

sql server

SUM(rating IN (4.5, 5))/COUNT(*)*100 AS pct_5_star,
SUM(CASE WHEN rating IN (4.5, 5) THEN rating ELSE 0 END) AS in_5_star

I don't know why I am finding it difficult to understand what exactly is happening in the above statement and what exactly is /COUNT(*)*100 doing here.

Best Answer

COUNT(*)*100 in this scenario seems to be how the developer dynamically gets the percentage based on how many records are returned.

Maybe it's better read this way:

((
    SUM(rating IN (4.5,5)) --SUM of ratings of 4.5 and 5
    /  --divided by
    COUNT(*)  --The total number of records
  )
*100) --Multiplied by 100 to make it readable as a percentage
AS pct_5_star

So if the query returns 100 records, it divides the SUM by 100 then multiplies thatresult by 100 to get an easily readable number.

if the query returns 150 records, it divides the SUM by 150 then multiplies that result by 100 to get an easily readable number.