SQL从另一个表中选择评级的平均值

时间:2013-05-19 06:03:40

标签: sql sql-server average

我有两个表:Anime_List和Anime_Reviews。

Anime_List表有一个'Rating'字段,可以从Anime_Reviews中获取平均评分。但是,Anime_Reviews中不存在某些评级(行),因此我的当前查询仅返回具有平均评分的标题。

SELECT Anime_List.AnimeID, Anime_List.Name, Anime_List.AnimeImage, Anime_List.Synopsis, Anime_List.Type, Anime_List.Episodes, Anime_List.Genres, AVG(Anime_Reviews.Rating) 
FROM Anime_List INNER JOIN Anime_Reviews ON Anime_List.AnimeID = Anime_Reviews.AnimeID
GROUP BY Anime_List.AnimeID, Anime_List.Name, Anime_List.AnimeImage, Anime_List.Synopsis, Anime_List.Type, Anime_List.Episodes, Anime_List.Genres

如果Anime_List中列出的每个标题的Anime_Reviews中没有评级(行),如何返回0.0的值?

enter image description here

2 个答案:

答案 0 :(得分:5)

使用子查询的版本

SELECT l.AnimeID, 
       l.Name, 
       l.AnimeImage, 
       l.Synopsis, 
       l.Type, 
       l.Episodes, 
       l.Genres, 
       (SELECT ISNULL(AVG(Rating), 0) Rating
          FROM Anime_Reviews 
         WHERE AnimeID = l.AnimeID)
  FROM Anime_List l

答案 1 :(得分:2)

LEFT JOINCOALESCE

一起使用
SELECT 
  l.AnimeID, 
  l.Name, 
  l.AnimeImage, 
  l.Synopsis, 
  l.Type, 
  l.Episodes, 
  l.Genres, 
  COALESCE(AVG(r.Rating), 0) AS Rating 
FROM Anime_List AS l
LEFT JOIN Anime_Reviews AS r ON l.AnimeID = r.AnimeID
GROUP BY l.AnimeID, 
         l.Name, 
         l.AnimeImage, 
         l.Synopsis, 
         l.Type, 
         l.Episodes, 
         l.Genres;

有关不同类型的SQL JOIN的详细信息,请参阅此文章: