Sql 每行总和和筛选结果总和,单位为$x
我的表格在Postgres中的数据:Sql 每行总和和筛选结果总和,单位为$x,sql,postgresql,Sql,Postgresql,我的表格在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:5
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、用户id、销售金额、销售货币id,状态为0,类型为0,并以$x的形式汇总到当前行,按订单按购买金额/销售金额ASC、日期添加ASC
$x=6的结果
你需要一个累计金额,这是Postgres提供的。这样的逻辑就有点复杂了。您需要大于或等于$x的第一个值
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
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;