这个问题的灵感来自于这个问题集(问题11的扩展)。
我有一个关系数据库,它由三个表组成,这三个表是相应连接的:
bands (id, name)
albums (id, name, release_year, band_id)
songs (id, name, length, album_id)
主键和外键是列名称所暗示的内容。
我想选择每张专辑中最长的歌曲并显示专辑、发行年份、歌曲的时长和名称。如果我省略最后一列,这个查询就会完成这项工作:
-- Select the longest Song of each Album --
SELECT
albums.name AS 'Album',
albums.release_year AS 'Release Year',
MAX(songs.length) AS 'Duration'
FROM albums
JOIN songs ON songs.album_id = albums.id
GROUP BY albums.name, albums.release_year;
但是,分组时,无法显示
name
列,因为它不是 GROUP
的一部分(因为每首歌曲名称都是唯一的,因此不会对任何元素进行分组)或聚合函数的一部分。
是否也可以显示最长歌曲的名称,如果可以,我应该在查询中添加什么?
您可以使用
MAX
代替 GROUP BY
和 ROW_NUMBER()
,然后过滤:
WITH agg AS
(
SELECT
a.name AS Album,
a.release_year AS [Release Year],
s.name AS Song,
s.duration AS Duration,
r = ROW_NUMBER() OVER (PARTITION BY s.album_id ORDER BY s.duration DESC)
FROM dbo.albums AS a
INNER JOIN dbo.songs AS s
ON s.album_id = a.id
)
SELECT Album,
[Release Year],
Song,
Duration
FROM agg
WHERE r = 1;