假设我的表中有以下数据;
tran_date withdraw deposit
25/11/2010 0 500
2/12/2010 100 0
15/12/2010 0 300
18/12/2010 0 200
25/12/2010 200 0
假设我想获得以下日期范围在 1/12/2010 和 31/12/2010 之间的数据。
tran_date withdraw deposit balance days_since_last_tran
1/12/2010 0 0 500 0
2/12/2010 100 0 400 1
15/12/2010 0 300 700 13
18/12/2010 0 200 900 3
25/12/2010 200 0 700 7
31/12/2010 0 0 700 6
这在 PostgreSQL 8.4 中可行吗?
最佳答案
使用:
SELECT t.tran_date,
t.withdraw,
t.deposit,
(SELECT SUM(y.deposit) - SUM(y.withdrawl)
FROM YOUR_TABLE y
WHERE y.tran_date <= t.tran_date) AS balance,
t.tran_date - COALESCE(LAG(t.tran_date) OVER(ORDER BY t.tran_date),
t.tran_date) AS days_since_last
FROM YOUR_TABLE t
8.4+ 很好,提供 access to analytic/windowing functions like LAG .
关于sql - Postgres问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4487036/