首先,我使用派生表來計算統計。這樣可以更容易地將零值轉換爲零(儘管如果我們在這裏使用Inner Join,則無需在TotalReviews上使用Coalesce)。
Select m.*
, Coalesce(MovieStats.TotalReviews, 0) As TotalReviews
, Coalesce(MovieStats.AverageRating, 0) As AverageRating
From Movie As m
Join (
Select R1.MovieId
, Count(*) As TotalReviews
, AVG((r.StoryRating + r.HumorRating + r.ActingRating)/3) As AverageRating
From MovieReview As r1
Group By R1.MovieId
) As MovieStats
On MovieStats.MovieId = m.Id
Where MovieStats.AverageRating Between @LowestRating And @HighestRating
唯一這裏的問題是,通過把我們的過濾器在where子句中,這意味着我們必須在給定範圍內AverageRating值MovieReview記錄。
Select m.*
, Coalesce(MovieStats.TotalReviews, 0) As TotalReviews
, Coalesce(MovieStats.AverageRating, 0) As AverageRating
From Movie As m
Left Join (
Select R1.MovieId
, Count(*) As TotalReviews
, AVG((r.StoryRating + r.HumorRating + r.ActingRating)/3) As AverageRating
From MovieReview As r1
Group By R1.MovieId
) As MovieStats
On MovieStats.MovieId = m.Id
And MovieStats.AverageRating Between @LowestRating And @HighestRating
在沒有電影評級或電影評級存在超出傳遞範圍的情況下,這將返回零。
另一種可能性是在具有評價和強迫那些有在傳遞的範圍內平均收視值過濾:
Select m.*
, Coalesce(MovieStats.TotalReviews, 0) As TotalReviews
, Coalesce(MovieStats.AverageRating, 0) As AverageRating
From Movie As m
Left Join (
Select R1.MovieId
, Count(*) As TotalReviews
, AVG((r.StoryRating + r.HumorRating + r.ActingRating)/3) As AverageRating
From MovieReview As r1
Group By R1.MovieId
) As MovieStats
On MovieStats.MovieId = m.Id
Where MovieStats.MovieId Is Null
Or (MovieStats.AverageRating Between @LowestRating And @HighestRating)
做你想做的事時AverageRating是零呢? – eKek0 2010-05-17 20:33:47