gpt4 book ai didi

SQL Server - 对整个列求和并分组

转载 作者:行者123 更新时间:2023-12-03 00:02:52 24 4
gpt4 key购买 nike

假设我在 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

参见SQL Fiddle with Demo

结果是:

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

关于SQL Server - 对整个列求和并分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com