一尘不染

SQL用AVG联接两个表

sql

我正在尝试加入两个表:

songs
id | song | artist
---|------|-------
1  | foo  | bar
2  | fuu  | bor
3  | fyy  | bir

score
id | score
---|------
1  | 2
2  | 4
3  | 8
2  | 6
3  | 2

使用以下SQL命令:

SELECT songs.id, songs.song, songs.artist, score.score FROM songs LEFT JOIN score ON score.id=songs.id ORDER BY songs.id, score DESC

我得到的是同一首歌曲的重复,并带有多个乐谱,我希望将乐谱平均。

result
id | song | artist | score
---|------|--------|-------
1  | foo  | bar    | 2
2  | fuu  | bor    | 4
2  | fuu  | bor    | 6
3  | fyy  | bir    | 8
3  | fyy  | bir    | 2

我尝试使用:

SELECT songs.id, songs.song, songs.artist, ROUND(AVG(score.score),1) AS 'score' FROM songs INNER JOIN score ON score.id=songs.id ORDER BY score DESC

但这平均所有分数,而不仅仅是每首歌曲的分数

result
id | song | artist | score
---|------|--------|-------
1  | foo  | bar    | 4.4

阅读 136

收藏
2021-03-17

共1个答案

一尘不染

您需要对要保留的所有字段进行GROUP BY:

SELECT songs.id, songs.song, songs.artist, 
    AVG(score.score * 1.0) AS AvgScore
FROM songs 
    LEFT JOIN score 
        ON score.id=songs.id 
GROUP BY songs.id, songs.song, songs.artist
ORDER BY songs.id, score DESC

或者,您可以执行以下操作:

SELECT songs.id, songs.song, songs.artist, 
    (SELECT AVG(Score) FROM score WHERE score.id = songs.id) AS AvgScore)
FROM songs
2021-03-17