SQL Sum行数,直到满足条件

时间:2017-09-08 18:33:21

标签: mysql sql database

所以在我的数据库中我有两行:Barcode,Profit; 根据利润,它们按降序排列,例如:

Barcode , Profit:
101 , 10000
106 , 9999
107 , 8888
108 , 222

我需要sql查询,它将执行以下操作: 我需要总结所有利润,然后查看其%80值,然后开始汇总条形码值,直到满足%80,例如:

Barcode , Profit:
101 , 10000
106 , 9999
107 , 8888
108 , 222

10000 + 9999 + 8888 + 222 = 29109

29109是总和,其%80 = 23 287,2

由于10000 + 9999 + 8888确实包含%80,结果应返回:

Barcode
101
106
107

1 个答案:

答案 0 :(得分:2)

您可以使用变量执行此操作:

select t.*
from (select t.*, (@sump := @sump + profit) as running_profit
      from t cross join
           (select @sump := 0) params
      order by profit desc
     ) t
where running_profit < 0.8 * @sump;

内部查询计算累积利润。作为副作用,它还计算利润的总和。

外部where选择第一行之前超过80%阈值的所有行。

相关问题