[数据库] 取指定表中某字段的累加和不超过总和80%的行
有表 Table_1, 字段 Value int, P float 。5
要取出以 Value 字段倒序的 P 字段累加和 不超过 整个表中P字段总和的 80%的行。 并在返回列表中 加入字段 SUM ,存放当前行与前面所有行的累加和。
折腾了半天, 写了下面的查询sql:
declare @e float select @e = sum(P) from [Table_1] Set @e = @e * 0.8 ;with T as ( select [ID] = row_number() over(order by [Value] desc), [Value], [P], (select sum(P) from [Table_1] a where a.[Value] >= b.[Value]) 'SUM' from [Table_1] b ) select * from T where [SUM] <= @e
共生成了 1.1 万行测试数据, 测试用试 12 秒, 运行效果图和原数据如上图所示。
有人写出了百万行只要14秒的sql:
select CollectData as value,0.00000 as P,0.00000 as _P into #data from (select top 1000000 * from EMS_HisData18) xx order by CollectData desc declare @sum decimal(18,8) declare @p decimal(18,8)=0.80 select @sum=sum(value) from #data update #data set @p=@p-(value/@sum),_P=@p select * from #data where _P>=0 drop table #data