计算单列的百分比

时间:2016-05-19 06:30:48

标签: sql database sqlite

所以我想要的结果是'Tracks'%显示每个类型的曲目总数百分比

SELECT Genre.Name, Count (Genre.GenreID) as 'No Of Tracks', 
(Genre.GenreID) as '% of Tracks' 
From Genre, Track
Where Genre.GenreID = Track.GenreID
Group by Genre.Name

不确定我是否正确设置会欣赏一些建议

3 个答案:

答案 0 :(得分:0)

SELECT Genre.Name, COUNT(Genre.GenreID) AS 'No Of Tracks', 
    ROUND(100.0 * COUNT(Genre.GenreID) / (SELECT COUNT(*) FROM Tracks), 2) AS '% of Tracks' 
FROM Genre
LEFT JOIN Track
    ON Track.GenreID = Genre.GenreID
GROUP BY Genre.Name

请注意,我已使用明确的连接替换了您的连接。此外,查询SELECT COUNT(*) FROM Genre不相关,因此查询优化器应该能够在执行时利用它。

答案 1 :(得分:0)

您必须将每Track的{​​{1}}个数除以Genre的总数:

Tracks

注意:

  1. 使用SELECT g.Name, COUNT(*) AS 'No of Tracks', (COUNT(*) * 100.0) / (SELECT COUNT(*) FROM Tracks) AS '% of Tracks' FROM Genre g LEFT JOIN Tracks t ON t.GenreID = g.GenreID GROUP BY g.GenreID, g.Name 语法代替旧式(使用逗号)。
  2. 使用含义全表别名来提高可读性。

答案 2 :(得分:0)

要获得每种类型的曲目数量,您需要按GenreID对曲目进行分组,并将该数量除以曲目总数:

SELECT Genre.Name AS Genre, 
       CONVERT(nvarchar, CAST(100.00*COUNT(Tracks.TrackId)/(SELECT COUNT(*) FROM Tracks) AS decimal(8,2))) + '%' AS 'Of Total Tracks'
FROM Genre
INNER JOIN Tracks ON (Genre.GenreId = Tracks.GenreId)
GROUP BY Tracks.GenreId, Genre.Name

这会给你(例如)这个结果:

Genre      Of Total Tracks
---------- -------------------------------
Classic    16.67%
Pop        33.33%
Rock       50.00%