我的表格在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
我必须从此表中选择id
,user_id
,sell_amount
,sell_currency_id
status=0
和type=0
以及SUM
}到当前行IN $ x,按ORDER BY
buy_amount/sell_amount ASC
排序,date_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
答案 0 :(得分: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;