我正在写一个看起来像这样的查询:
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。
答案 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;