(我正在使用 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';
我如何找到余额(截至该时间点的 amount
总和)等于某个值(对我来说最有趣的值是 0,但一般的解决方案会很好)?
我知道涉及将 balance
反规范化到其自己的列中的解决方案。由于其他原因,我不想这样做,所以我正在寻找使用上述架构的建议。
最佳答案
试试这个:
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
关于sql - 查找截至该时间的所有记录上某列的 SUM 为某个值的时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11116082/