尝试生成包含曲目数量和属于该流派的曲目百分比的流派列表。所有磁道都不应按升序排列。
输出应该像这样,有3个独立的列。
Genre No.of Tracks % of Tracks
Rock 5 20%
Genre table consists of - GenreId , Name
Track table consists of - TrackId, Name, GenreId
最佳答案
SELECT g.nameOfGenre,
COUNT(t.TrackId) AS tracks_count,
COUNT(t.TrackId) / tt.total_tracks * 100 AS tracks_percent
FROM Genre g
LEFT JOIN Track t ON t.GenreId = g.genreId
JOIN (SELECT COUNT(*) AS total_tracks FROM Track) AS tt
GROUP BY g.genreId
简单的例子。如果你愿意的话,你可以把百分比四舍五入。
关于mysql - 在SQL中生成一个列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37177300/