Monday, February 13, 2012

Average

Hello,

I have two tables:
[Posts] > PostId, ...
[Ratings] > RatingId, PostId, Rating

I want to select all posts and add a new column named AverageRating.
This new column is the average of all ratings associated to that Post.
If a post was not rated then its AverageRating would be NULL.

How can I do this?
Thanks,
Miguel

select* , (SelectAvg(Rating)FROM Ratings RWhere R.PostId= P.PostId)as AverageRating

from Posts P

|||

SELECT p.*, t.avgRatingFROM posts pLEFTJOIN(Select postid,CAST(AVG(CAST(RatingasDecimal(5,2)))asDecimal(5,2))AS avgRatingFROM RatingsGroup By postid) tON p.postid=t.postid

No comments:

Post a Comment