SQL Server计算每行的值百分比

时间:2015-12-28 12:06:18

标签: sql sql-server select

我有一个返回表格的查询:

Value    Description
--------------------
12       Decription1
43       Decription2
78       Decription3
3        Decription4
6        Decription5

我的select看起来像

select 
    sum(value), description 
from 
    table 
group by 
    description

有5行,所有5行的总和是169,这是100%,现在我想知道第一行有多少%,第二行等等,我知道公式是例如for第一排12 * 100/169。如何在我的查询中执行此操作。

谢谢!

4 个答案:

答案 0 :(得分:2)

declare @total int;
select @total = Sum(Value) from table

select (sum(value) * 100.0)/@total as percentage , description 
    from table 
      group by description` 

答案 1 :(得分:2)

select description , value,pcnt =  100.*value / (sum(value) over ( )) 
    from table 

答案 2 :(得分:1)

您可以使用窗口功能执行此操作:

select description, sum(value),
       sum(value) * 100.0 / sum(sum(value)) over () as percentage
from table
group by description;

答案 3 :(得分:0)

您可以使用窗口函数:

SELECT *,
    [percentage] = ROUND(100 * 1.0 * value / SUM(value) OVER(), 0)
FROM #tab;

LiveDemo

输出:

╔═══════╦═════════════╦════════════╗
║ value ║ Description ║ Percentage ║
╠═══════╬═════════════╬════════════╣
║    12 ║ Decription1 ║          8 ║
║    43 ║ Decription2 ║         30 ║
║    78 ║ Decription3 ║         55 ║
║     3 ║ Decription4 ║          2 ║
║     6 ║ Decription5 ║          4 ║
╚═══════╩═════════════╩════════════╝