计算列上的窗函数

问题描述 投票:1回答:1

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

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。

sql postgresql window-functions postgresql-10
1个回答
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;
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.