2

I have this table "Ratings" containing an USER_ID, Artist_ID and a Rating (int, the score assigned by a user). And of course a table "Artists" with among others a field "ID" and "Name".

I am trying to get a descending list with artistnames, sorted by the AVG score per artists. First I thought this wouldn't be this hard, but I keep on fiddling...

Here's where I'm stuck. I have to figure out how it can calculate the AVG() of the id's that occur multiple times. And I've tried a variety of queries using the DISTINCT keyword but gained no success.

For example:

SELECT Name, Rating
FROM Artists as a
INNER JOIN Ratings as r
ON a.ID = r.Artists_ID 
ORDER BY r.Rating DESC;

Gives me the result:

Name                Rating
"The Mars Volta"    9.5
"Simon Felice"      9.0
"Laura Gibson"      8.0
"Calexico"          7.0
"Mira"              7.0
"Guido Belcanto"    6.0
"Guido Belcanto"    1.0

As you can see, the artist "Guido Belcanto" has more than 1 rating. I have no clue at the moment on how to calculate the AVG() of those ID's that occur more than once. It's probably basic MySQL but I'm maybe searching in the wrong direction

4

2 回答 2

3

您在查询中忘记了 aGROUP BY并实际计算了您获得的平均评分(使用AVG函数):

SELECT Name, AVG(Rating) AS AVGRating
FROM Artists as a
INNER JOIN Ratings as r
    ON a.ID = r.Artists_ID
GROUP BY Name
ORDER BY AVGRating DESC;

尽管在艺术家表的键上进行分组可能更好(有足够的数据,有几个同名的艺术家并不是不可想象的)。

于 2012-05-22T00:39:50.207 回答
0

按艺术家对评分进行分组,以便您可以计算每个组的评分平均值,并将其与 Artists 连接以获得与每个 id 关联的名称。

于 2012-05-22T00:40:43.010 回答