SQL用AVG联接两个表

编程入门 行业动态 更新时间:2024-10-11 09:21:39
本文介绍了SQL用AVG联接两个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正试图联接两个表:

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

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

What I get back is duplicates of the same song with multiple scores, I would like the score to be averaged.

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

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

But that averages all scores, not just the score of each individual song

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

推荐答案

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

You need to GROUP BY all the fields you want to retain:

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

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

Alternatively, you could just do this:

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

更多推荐

SQL用AVG联接两个表

本文发布于:2023-11-22 01:17:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615406.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   SQL   AVG

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!