SQL Server - 对整个列和“分组依据”求和

时间:2013-01-16 16:37:13

标签: sql sql-server

假设我在SQL Server中有以下表:

grp:     val:     criteria:
a        1        1
a        1        1
b        1        1
b        1        1
b        1        1
c        1        1
c        1        1
c        1        1
d        1        1

现在我想要的是获得一个基本上是:

的输出
Select grp, val / [sum(val) for all records] grouped by grp where criteria = 1

所以,鉴于以下情况属实:

Sum of all values = 9
Sum of values in grp(a) = 2
Sum of values in grp(b) = 3
Sum of values in grp(c) = 3
Sum of values in grp(d) = 1

输出如下:

grp:     calc:    
a        2/9        
b        3/9        
c        3/9        
d        1/9

我的SQL必须是什么样的?

谢谢!

2 个答案:

答案 0 :(得分:5)

您应该可以使用sum() over()

这样的内容
select distinct grp,
  sum(val) over(partition by grp)
    / (sum(val) over(partition by criteria)*1.0) Total
from yourtable 
where criteria = 1

请参阅SQL Fiddle with Demo

结果是:

| GRP |          TOTAL |
------------------------
|   a | 0.222222222222 |
|   b | 0.333333333333 |
|   c | 0.333333333333 |
|   d | 0.111111111111 |

答案 1 :(得分:1)

我完全同意@ bluefeet的回复 - 这只是一个与数据库无关的方法(应该适用于大多数RDBMS):

select distinct
  grp,
  sum(val)/cast(total as decimal)
from yourtable 
cross join 
(
  select SUM(val) as total 
  from yourtable
) sumtable
where criteria = 1
GROUP BY grp, total

这是SQL Fiddle