计算列上的窗口函数

时间:2019-03-29 08:18:27

标签: sql postgresql window-functions postgresql-10

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

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

如您所见,我正在使用窗口函数来获取child.amount上的运行总计。

问题是,是否有任何标准或非标准的方式引用child_sum而不在窗口函数sum中复制其表达式?

我正在使用Postgres 10。

1 个答案:

答案 0 :(得分:1)

您可以使用子查询:

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;