假设我有一个名为transaction的表,包含transaction_date,deposit,withdraw字段.一天可能有也可能没有交易,但每天可以有多笔交易.所以,我需要做的是给出一个日期范围,比如说2010年12月1日到2010年12月31日,我需要计算出每天的最低余额.我们假设在2010年12月1日之前也有交易.有人能给我一个关于这个的想法吗?
谢谢.
更新示例
tran_date withdraw deposit
2010-11-23 0.00 50.00
2010-12-10 0.00 50.00
2010-12-10 0.00 200.00
2010-12-12 100.00 0.00
2010-12-20 0.00 50.00
2010-12-20 70.00 0.00
2010-12-20 0.00 50.00
2010-12-20 0.00 50.00
2010-12-24 150.00 0.00
在上面的例子中,从12月1日到12月10日的最低每日余额为50.在12月10日,有两个存款总计70,但当天的最低余额为50(从前一天结转).
现在让我们看看多个交易.
12月20日的结转是200.第一次存款使其为250,第二次存款使其为180,第三次存款使其为230,最后一次交易使其为280.因此,撤销后当天的最低存款为180当日第二笔交易70.是否可以使用Postgresql 8.4上的查询生成它,还是应该使用其他方法?
解决方法:
EDIT2
这是一个完整的例子,包括前一天的(最小)余额(据我所知,这么小的一组数据).它应该在8.4上运行.
我重构派生表以使用CTE(公用表表达式)使它(希望)更具可读性:
WITH days AS ( -- generate a liste of possible dates spanning -- the whole interval of the transactions SELECT min(tran_date) + generate_series(0, max(tran_date) - min(tran_date)) AS some_date FROM transaction ), total_balance AS ( -- Calculate the running totals for all transactions SELECT tran_id, days.some_date as tran_date, deposit, withdrawal, sum(deposit - withdrawal) OVER (ORDER BY some_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as balance FROM days LEFT JOIN transaction t ON t.tran_date = days.some_date ), min_balance AS ( -- calculate the minimum balance for each day -- (the smalles balance will have a '1' in the column balance_rank) SELECT tran_id, tran_date, rank() OVER (PARTITION BY tran_date ORDER BY balance) as balance_rank, balance FROM total_balance ) -- Now get everything, including the balance for the prevIoUs day SELECT tran_id, tran_date, balance, lag(balance) over (order by tran_date) as prevIoUs_balance FROM min_balance WHERE balance_rank = 1;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。