所以我想結果是「%曲目」顯示曲目計算百分比單列
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
不知道總數的各流派的百分比,如果我把它正確地希望得到一些建議
所以我想結果是「%曲目」顯示曲目計算百分比單列
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
不知道總數的各流派的百分比,如果我把它正確地希望得到一些建議
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
不相關,所以查詢優化器在執行時應該能夠利用這一點。
你必須與Tracks
總數每Genre
劃分的Track
S中的計數:
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
注:
JOIN
語法(使用逗號) 。,讓每流派的磁道數您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%
它應該是顯式的而不是隱式的。我很困惑。 –
顯式是一個髒字,所以我用隱式代替:-) –
啊哈!出於同樣的原因,我故意從我的答案中刪除了這個詞。 ;) –