简体   繁体   中英

SQL, Databases, Joining two tables, get average

I have two tables one called Hotels and one called Ratings. I want to display the hotel names and then get the average rating for each hotel and display this. In the ratings table I might have 5 different ratings of a hotel so I want the average number and then display this. How would my query have to look like ?

You didn't provide details but I assume you have a primary key in Hotels which is a foreign key in Ratings ( HotelId ). You didn't specify your RDBMS but each one should have a function to average and the query will look like:

select h.HotelId, avg(r.Rating)
from Hotels h
inner join Ratings r on h.HotelId = r.HotelId
group by h.HotelId

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