在postgresql上获取日期限制的运行总计

时间:2014-10-29 15:11:11

标签: postgresql

我在Postgresql 9.3上运行了一个数据库查询,看起来像是为了获得会计分录的运行余额:

select  *,(sum(amount) over(partition 
by
    ae.account_id 
order by 
    ae.date_posted,
    ae.account_id
  )) as formula0_1_ 
from
    account_entry as ae 
--    where ae.date_posted> '2014-01-01'
order by account_id desc, date_posted asc 

没有where子句的预期输出将是:

id | date         | amount | running balance
 1    2014-01-01      10          10
 2    2014-01-02      10          20

我使用where子句获得的内容:

id | date         | amount | running balance
 2    2014-01-02      10          10

如果我尝试按日期范围过滤(上面评论的位),我怎样才能使此查询返回相同的正确结果?

1 个答案:

答案 0 :(得分:1)

您需要先在所有数据上选择并计算运行余额,然后在外部WHERE中添加SELECT子句。

SELECT
  *
FROM
  (SELECT
    *,
    SUM(amount) OVER (
      PARTITION BY
        ae.account_id
      ORDER BY
        ae.date_posted,
        ae.account_id
    ) AS formula0_1_
  FROM
    account_entry AS ae) AS total
WHERE
  total.date_posted > '2014-01-01'
ORDER BY
  account_id DESC,
  date_posted ASC;