与SQL中的列总和相关的每一行的百分比值

时间:2018-08-23 13:50:08

标签: sql sql-server tsql

我有一个看起来像这样的查询:

SELECT dbo.music_styles.music, (COUNT(dbo.people.id)* 100.00 / (SELECT SUM(dbo.people.id)))  AS nbStyle
FROM dbo.people_music_styles
INNER JOIN dbo.music_styles ON dbo.music_styles.id = dbo.people_music_styles.id_music_styles
WHERE dbo.people.age BETWEEN @age_min and @age_max 
AND dbo.people.gender = @gender
GROUP BY dbo.music_styles.music
ORDER BY nbStyle DESC

在响应中,我得到一个包含两列的数组:

  • 带有样式名称的人(感谢加入)
  • 另一列,其中包含有关我设置的参数的样式出现在关系表中的次数。

我想要第三列,其中第三行的值与该列的总数/总和以及样式显示的次数有关。

2 个答案:

答案 0 :(得分:0)

由于这将需要分数,因此请务必进行转换,以免截断为整数:

(COUNT(DISTINCT dbo.music_styles.id) / CONVERT(FLOAT, COUNT(SELECT SUM(dbo.music_styles) FROM dbo.music_styles))) * 100

让我知道这是否行得通,否则,我很乐意进一步探索。

答案 1 :(得分:0)

@CarlosBos我终于设法通过您的提案的一部分找到了可行的答案! 这是代码:

SELECT dbo.music_styles.music, COUNT(dbo.people.id) AS peopleID, CONVERT(FLOAT, ROUND(COUNT(dbo.people.id)* 100.00 / SUM(COUNT(dbo.people.id)) OVER (), 2)) AS Répartition
FROM dbo.people_music_styles
INNER JOIN dbo.people ON dbo.people.id = dbo.people_music_styles.id_people
INNER JOIN dbo.music_styles ON dbo.music_styles.id = dbo.people_music_styles.id_music_styles
WHERE dbo.people.age BETWEEN @age_min and @age_max 
AND dbo.people.gender = @gender
GROUP BY dbo.music_styles.music
ORDER BY peopleID DESC

非常感谢!