sql - Postgres问题

标签 sql postgresql

假设我的表中有以下数据;

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/

相关文章:

postgresql - 在函数中返回多个值

python - ISBN 用作主键,现在我想将非书籍内容添加到数据库中 - 我应该迁移到 EAN 吗?

postgresql - 如何在Cloud9上使用Rails Composer和postgreSQL并在Heroku上进行部署

php - 通过添加第二个查询真的可以实现 SQL 注入(inject)吗?

sql - 如何合并两个 MySQL 表?

postgresql - 将数据从 Cassandra 传输到 Postgresql

sql - Rails 迭代查询到 SQL 语句

mysql - 大文件使用什么数据库

sql - 获取不在数据库中的范围

mysql - Mysql 的 Max 函数不返回列的最大值。按限制订购也不起作用