2014-02-18 24 views
1

我的表的數據,Postgres的:

id user_id sell_amount sell_currency_id buy_amount buy_currency_id type status date_add 
5 2 2.00000000 1 4.00000000 0 0 0 2013-12-15 19:06:40 
6 3 2.60000000 1 5.10000000 0 0 0 2013-12-15 19:06:54 
4 1 1.00000000 1 0.80000000 0 0 0 2013-12-15 19:07:05 
7 4 4.00000000 1 8.20000000 0 0 0 2013-12-15 19:07:21 
8 5 3.00000000 1 6.00000000 0 1 0 2013-12-15 19:07:40 

我必須選擇iduser_idsell_amountsell_currency_id從這個表是status=0type=0SUM到當前行在$ X,以便通過ORDER BYbuy_amount/sell_amount ASCdate_add ASC

結果爲$x = 6

id user_id sell_amount sell_currency_id SUM(sell_amount) 
4 1 1.00000000 1 1.00000000 
6 3 2.60000000 1 3.60000000 
5 2 2.00000000 1 5.60000000 
7 4 4.00000000 1 9.60000000 

回答

3

您需要一個累計和,Postgres提供。這個邏輯有點棘手。您需要第一個大於或等於$x的值。

select id, user_id, sell_amount, sell_currency 
from (select id, user_id, sell_amount, sell_currency, 
      sum(sell_amount) over (order by buy_amount/sell_amount ASC, date_add ASC) as cumsell 
     from table t 
     where status = 0 and type = 0 
    ) t 
where $x <= cumsell and $x > cumsell - sell_amount;