获取某些记录,而以前的记录总和大于SQL Server中的百分比

时间:2011-09-01 04:55:35

标签: sql sql-server tsql

表:FooData

ID   Count
1    54
2    42
3    33
4    25
5    16
6    9
8    5
9    3
10   2

我想获取Count列的总和大于某个百分比的记录,如90.

对于这个例子,所有记录的总和是189,其中90%是170.1,我们可以看到ID 1到6的总和是179,它大于170.1所以记录ID 6应该是返回。

顺便说一下,不允许使用临时表,因为我需要在函数中执行它。

2 个答案:

答案 0 :(得分:3)

三角形连接的另一个版本。

declare @T table(ID int primary key, [Count] int)
insert into @T values (1, 54), (2, 42), (3, 33),(4, 25), (5, 16), (6, 9), (8, 5), (9, 3),(10, 2)

;with R(ID, [Count], Running) as
(
  select T1.ID, 
         T1.[Count],
         cast(T3.[Count] as float)
  from @T as T1
    cross apply (select sum(T2.[Count])
                 from @T as T2
                 where T1.ID >= T2.ID) as T3([Count])
),
T(Total) as
(
  select sum([Count])
  from @T
)
select top 1 R.ID, R.[Count], R.Running
from R
  inner join T
    on R.Running / T.Total > 0.9
order by R.ID

答案 1 :(得分:1)

试试这个:

SELECT TOP 1 
  t2.id,
  SUM(t1.value) AS runningTotal
FROM FooData t1 
INNER JOIN FooData t2 
  ON t1.id <= t2.id 
GROUP BY t2.id
HAVING SUM(t1.value) * 100. / 
  (SELECT SUM(value) FROM @FooData) > 90
ORDER BY SUM(t1.value)

但请注意triangular joins in running totals的潜在性能问题。