SQL - Get AVG from count from another table -
so have 2 tables: listing , reviews. try listing best reviews, based in state. need avg reviews listing , desc listings.
table structure: listing: id; title; state; ...
reviews: id; listing_id; rating (from 1-5)
i solve desc listing of reviews try avg of rating of reviews.
select *, (select count(*) reviews rv ls.id = rv.listing_id) count listing ls ls.state ='$get_state' order count desc
sample data:
listing: id title state 1 hotel nice view arizona 2 hotel stay arizona review: id listing_id rating 1 1 4(stars) 2 1 4(stars) 3 1 3(stars) 4 2 5(stars)
listing id 1 got 3 reviews , total star value of 11 / 3 reviews = 3.6 stars
listing id 2 got 1 review , total star value of 5 / 1 = 5 stars
now should first listing 2 , listing 1 want display whole thing on php page.
what can next? help
you can use avg() function average rating
select ls.id, title, state, round(avg(rating),2) avg_rating listing ls join review rv on ls.id = rv.listing_id ls.state = '$get_state' group ls.id, title, state order avg_rating desc
if using mssql, cast column rating decimal precision (as float or decimal)
round(avg(cast(rating float)),2) avg_rating
Comments
Post a Comment