Click here to Skip to main content
15,886,038 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
<pre lang="text">I have two tables
  
 Rating   RatingDescription
      1         poor
      2         good
      3         vgood
      4         excellent 



Customer       Rating
       1            1
       1            2
       2            5
       3            3
       3            3


Now i want to get the average rating for each customer

Customer AvgRating   RatingDescription
1          1.5         bad
3          3.5      very good(if it was 3.9 it should be very good not excellent)
3          3         very good


What I have tried:

select
    max(Customer) as cust
	,max(RatingDetails.Description) as descr
	,AVG(CAST(testttt.rating AS float)) as RatingAvg
From customer
	join Rating 
		on Rating.Rating = floor(AVG(CAST(customer.rating AS float)))
group by customer



this might be simple data but i want to be able to take the integer value from the avg then take the desciprtion, i tried it with 'having' but no luck
Posted
Updated 13-Apr-20 8:18am

Try:
SQL
SELECT a.Customer, a.Average, b.RatingDescription
FROM (SELECT Customer, AVG(CAST(Rating AS FLOAT)) AS Average
      FROM Customer
      GROUP BY Customer) a 
JOIN Rating b ON CAST (a.Average AS INT) = b.Rating
But you will need to expand your Rating table to include all possible integer values!
 
Share this answer
 
Comments
Maciej Los 16-Apr-20 1:46am    
5ed!
You could also do this with a CTE, populating it with the Customer & Average Rating.
Then you would JOIN that CTE along with the Ratings table.

Proof of Concept:
SQL
DECLARE @Ratings TABLE ( Rating Decimal(5,1) NULL, RatingDesc NVARCHAR(16) NULL )
INSERT @Ratings VALUES (1, 'poor'), (2, 'good'), (3, 'v-good'), (4, 'excellent'), (5, 'Off the chart')

DECLARE @Reviews TABLE ( Customer INT NULL, Rating Decimal(5,1) NULL)
INSERT @Reviews VALUES (1, 1), (1,2), (2, 5), (3,3), (3,3)

; WITH cte AS (
     SELECT   Customer, AvgRating = Cast(Avg(Rating) as Decimal(5,1))
     FROM     @Reviews
     GROUP BY Customer
)

SELECT	 cte.*, rv.RatingDesc
FROM		 cte
INNER JOIN @Ratings rv
      ON   cte.AvgRating BETWEEN rv.Rating - 0.1 AND rv.Rating + 0.9
 
Share this answer
 
Comments
Maciej Los 16-Apr-20 1:46am    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900