window 计算列上的函数

window function over computed column

我正在编写一个看起来像这样的查询:

select parent.id,
       parent.date, 
       sum(child.amount) filter (where child.is_ok) as child_sum,
       sum(sum(child.amount) filter (where child.is_ok)) over (order by parent.date)
  from parent
  left join child on parent.id = child.parent_id
 group by parent.id, parent.date
 order by parent.date desc

如您所见,我正在使用 window 函数获得 运行 总计超过 child.amount

问题是,是否有任何标准或非标准的方法来引用 child_sum 而无需在 window 函数中复制其表达式 sum

我正在使用 Postgres 10。

您可以使用子查询:

SELECT id, date, child_sum,
       sum(child_sum) over (order by date)
FROM (SELECT parent.id,
             parent.date, 
             sum(child.amount) FILTER (WHERE child.is_ok) AS child_sum
      FROM parent
      LEFT JOIN child ON parent.id = child.parent_id
      GROUP BY parent.id, parent.date
     ) AS subq
ORDER BY date DESC;