假设我在 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 应该是什么样子?
谢谢!!
最佳答案
你应该能够使用像这样的东西,它使用 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
结果是:
| GRP | TOTAL |
------------------------
| a | 0.222222222222 |
| b | 0.333333333333 |
| c | 0.333333333333 |
| d | 0.111111111111 |
关于SQL Server - 对整个列求和并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363238/