I am designing a website that people post text messages. users can rate the messages (1 to 5). I’m recording this ratings into a table to:
- avoid multiple rating by one user for the same post
- to be able get the average rating of a post.
but I also the number of votes are important too. for example a post having 10 votes of 3 (makes 30) are valuable than the post with 2 votes of 5 (that makes 10). Now when I’m showing a page with 20 of this messages I want to show their rating too
This is my rating table:
create table ratings(
[id] int primary key identity(1,1),
[msgid] int,
[uid] int,
[rating] tinyint
)
I want to get to 20 messages from messages table with the sum of the ratings for each message and the count of ratings for each message.
select
msg.id, msg.text,
sum(rate.rating),
count(rate.id)
from
messages as msg
inner join
ratings as rate on msg.id = rate.msgid
group by
msg.id
can any one please help me with the SQL query code?
You cannot select columns which haven’t been used in
group byclause.Try: