SQL服务器行具有相对值?

时间:2012-03-23 12:42:06

标签: sql-server sql-server-2008 tsql

我有这张桌子:

Name   |  money_earned
_______________________

john   |   100
paul   |   200
ringo  |   300
george |   200

我想计算(以最强智能方式) - 每行附近的

百分比(每个披头士)的百分比 - 相对总和

所以我想要这样的结果:(总和是800)

Name   |  money_earned| his_Percentage
__________________________________

john   |   100        |   0.125
paul   |   200        |   0.25
ringo  |   300        |   0.375
george |   200        |   0.25

谢谢:)

修改

我很高兴有rollup这样的解决方案。

它计算总和,以及总和......就像这个函数一样。

因此,假设我想在1个查询中使用它而不声明额外的预先计算的值。

3 个答案:

答案 0 :(得分:3)

select Name,
       money_earned,
       money_earned / sum(money_earned) over() as his_Percentage
from [Table]

答案 1 :(得分:2)

试试这个(从性能角度来看,这种方式应该是最有效的)

DECLARE @sum INT
SELECT @sum = SUM(money_earned) FROM table

SELECT Name, money_earned, CAST(money_earned as float) / @sum as his_Percentage 
FROM table

OR

;WITH CTE AS (
    SELECT SUM(money_earned) as summ FROM table
)
    SELECT Name, money_earned, CAST(money_earned as float) / summ as his_Percentage 
    FROM table
    CROSS JOIN CTE

OR

SELECT Name, money_earned, 
    CAST(money_earned as float) / (SELECT SUM(money_earned) FROM table) as his_Percentage 
FROM table

答案 2 :(得分:2)

declare @t table(name varchar(10), money_earned int)

insert @t values('john',100 ),('paul',200 ),('ringo',300 ),('george',200)

select name, money_earned, 
cast(1.0 * money_earned / sum(money_earned) over () as numeric(4,3)) his_Percentage,
cast(100.0 * money_earned / sum(money_earned) over () as numeric(4,1)) REAL_his_Percentage
from @t

结果:

name       money_earned his_Percentage                REAL_his_Percentage
---------- ------------ ----------------------------- --------------------
john       100          0.125                         12.5
paul       200          0.250                         25.0
ringo      300          0.375                         37.5
george     200          0.250                         25.0