繁体   English   中英

SQL总和行号,直到满足条件

[英]SQL Sum Row number until condition is met

所以在我的数据库中,我有两行: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

您可以使用变量来做到这一点:

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%的阈值中的第一行的所有行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM