2017-09-08 69 views
-1

所以在我的數據庫中我有兩行:條碼,利潤; 他們是一個從高到低的順序,根據利潤,例如:SQL總行號,直到條件得到滿足

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不包含%80the結果應該返回:

Barcode 
101 
106 
107 

回答

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%閾值的第一行。