同一单元格中的多个值

时间:2016-05-20 01:09:10

标签: sql database sqlite

我正在尝试对曲目进行描述,包括与其相关的所有细节。

 SELECT 
(SELECT 
UPPER(Track.Name) || ' is a ' || 
CAST(Track.Milliseconds/1000 AS INT) || ' seconds long track in the album ' ||
UPPER(Album.Title) || ' of ' || 
Artist.Name || ' composed by ' || 
CASE WHEN Track.Composer IS NULL THEN 'an unknown composer' ELSE Track.Composer END ||
'. ' || 'It is available as a ' || 
MediaType.Name || ' for $' || 
Track.UnitPrice || ', and it can be found in the following playlists: ' ||
Playlist.Name )
AS 'Track Description' FROM Track
LEFT JOIN Album
ON Track.AlbumId=Album.AlbumId
INNER JOIN Artist
ON Artist.ArtistId=Album.ArtistId
INNER JOIN MediaType
ON Track.MediaTypeId=MediaType.MediaTypeId
INNER JOIN PlaylistTrack
ON PlaylistTrack.TrackId = Track.TrackId
INNER JOIN Playlist
ON Playlist.PlaylistId = PlaylistTrack.PlaylistId
ORDER BY RANDOM()
LIMIT 1;

我正在与playlist.name合作。一个曲目可以在多个播放列表中,目前它只输出顶部播放列表。我想知道如何在and it can be found in the following playlists: ' ||

之后输出所有播放列表,以逗号分隔轨道

1 个答案:

答案 0 :(得分:0)

一种策略是使用GROUP_CONCAT来聚合显示给定曲目的所有播放列表名称。为此,您可GROUP BY与播放列表名称​​除之外的每个列相关联。子查询以内部查询的漂亮格式计算输出。

SELECT UPPER(t.trackName) || ' is a ' || 
    CAST(t.trackMillis/1000 AS INT) || ' seconds long track in the album ' ||
    UPPER(t.albumTitle) || ' of ' || 
    t.artistName || ' composed by ' || 
    CASE WHEN t.trackComposer IS NULL THEN 'an unknown composer' ELSE t.trackComposer END ||
    '. ' || 'It is available as a ' || 
    t.mediaTypeName || ' for $' || 
    t.trackUnitPrice || ', and it can be found in the following playlists: ' || t.playlistNames
FROM
(
    SELECT Track.Name AS trackName, Track.Milliseconds AS trackMillis,
        Album.Title AS albumTitle, Artist.Name AS artistName,
        Track.Composer AS trackComposer, MediaType.Name AS mediaTypeName,
        Track.UnitPrice AS trackUnitPrice, GROUP_CONCAT(Playlist.Name) AS playlistNames
    FROM Track
    LEFT JOIN Album
        ON Track.AlbumId = Album.AlbumId
    INNER JOIN Artist
        ON Artist.ArtistId = Album.ArtistId
    INNER JOIN MediaType
        ON Track.MediaTypeId = MediaType.MediaTypeId
    INNER JOIN PlaylistTrack
        ON PlaylistTrack.TrackId = Track.TrackId
    INNER JOIN Playlist
        ON Playlist.PlaylistId = PlaylistTrack.PlaylistId
    GROUP BY Track.Name, Track.Milliseconds, Album.Title, Artist.Name,
        Track.Composer, MediaType.Name, Track.UnitPrice
) t