3

(我正在使用 PostgreSQL)

我有一个将交易存储到帐户的表。为了这个问题,想象它的结构如下:

create table transactions (
    timestamp timestamp with time zone not null,
    amount decimal(6,2) not null
);

任何时间点的余额可以通过以下方式获得:

select sum(amount) as balance from transactions where timestamp < 'point in time';

我怎样才能找到余额(amounts 到那个时间点的总和)等于某个值的所有时间段(对我来说最有趣的值是 0,但一般的解决方案会很好)?

我知道涉及非规范化balance到自己的列的解决方案。由于其他原因,我不希望这样做,所以我正在寻找使用上述模式的建议。

4

1 回答 1

1

试试这个:

select sum(amount) over(order by timestamp) as balance, timestamp 
from transactions where timestamp < 'point in time';

查找全零:

with a as
(
   select sum(amount) over(order by timestamp) as balance, timestamp
   from transactions where timestamp < 'point in time'
)
select * from a where balance = 0
于 2012-06-20T09:43:29.783 回答