5

假设我在 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 应该是什么样子?

谢谢!!

4

2 回答 2

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

结果是:

| GRP |          TOTAL |
------------------------
|   a | 0.222222222222 |
|   b | 0.333333333333 |
|   c | 0.333333333333 |
|   d | 0.111111111111 |
于 2013-01-16T16:45:10.493 回答
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

于 2013-01-16T16:58:20.593 回答