SQL - 两个列按MAX函数分组

时间:2018-05-29 11:34:38

标签: sql database postgresql max aggregate-functions

SELECT artist.name, recording.name, MAX(recording.length)
FROM recording 
INNER JOIN (artist_credit 
            INNER JOIN (artist_credit_name 
                        INNER JOIN artist 
                                ON artist_credit_name.artist_credit=artist.id)
                    ON artist_credit_name.artist_credit=artist_credit.id)
        ON recording.artist_credit=artist_credit.id
WHERE artist.gender=1 
  AND recording.length <= (SELECT MAX(recording.length) FROM recording)
GROUP BY artist.name, recording.name
ORDER BY artist.name

我们正在将MusicBrainz数据库用于学校,我们遇到了&#34; GROUP BY&#34;因为我们有两列(它适用于一列,但不适用于两列)。我们希望结果只显示一位具有第二长录音时间的艺术家,但代码会显示同一位艺术家每首歌曲的所有录音时间。 有什么建议?感谢。

2 个答案:

答案 0 :(得分:0)

您不需要多次查看连接条件。它们可以简化为一个连接,如下所示。

SELECT DISTINCT B.name, A.name, A.length
FROM recording A JOIN artist B
ON A.artist_credit=B.id
WHERE B.gender=1
AND A.length=(SELECT C.length FROM recording C    
              WHERE C.artist_credit=B.artist_credit 
              ORDER BY C.length LIMIT 1, 1)
ORDER BY B.name;

请参阅Using MySQL LIMIT to get the nth highest value

答案 1 :(得分:0)

正如其他人所指出的,可以减少join语句。在AND语句中运算符似乎也有问题;它应该是&lt;而不是&lt; =以获得第二高的长度(Se在这里:What is the simplest SQL Query to find the second largest value?)。

我建议您尝试以下方法:

SELECT artist.name, recording.name, MAX(recording.length)
FROM recording 
JOIN artist ON recording.artist_credit = artist.id
WHERE 
    artist.gender=1 
    AND 
    recording.length < (SELECT MAX(recording.length) FROM recording)
GROUP BY artist.name
ORDER BY artist.name