[英]Calculating percentages for single column
So the outcome i would like is for '% Of Tracks' to display each genres percentage of the total number of 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
Not sure if i set it up correctly would appreciate some advice 不知道我是否正确设置会喜欢一些建议
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
Note that I have replaced your join with an explicit one. 请注意,我已将您的联接替换为显式联接。 Also, the query
SELECT COUNT(*) FROM Genre
is not correlated, so the query optimizer should be able to take advantage of this when executing. 另外,查询
SELECT COUNT(*) FROM Genre
不相关,因此查询优化器在执行时应该能够利用这一点。
You have to divide the count of Track
s per Genre
with the total number of Tracks
: 您必须将每个
Genre
的Track
数除以Tracks
总数:
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
Notes: 笔记:
JOIN
syntax instead of the old-style (using comma). JOIN
语法而不是旧式(使用逗号)。 To get the number of tracks per genre you need to group the tracks by GenreID
and divide that count by the total number of tracks: 要获取每种流派的曲目数,您需要按
GenreID
对曲目进行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
This gives you (for example) this result: 这给您(例如)以下结果:
Genre Of Total Tracks
---------- -------------------------------
Classic 16.67%
Pop 33.33%
Rock 50.00%
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.