我可以借助窗口函数来计算总和吗?

时间:2020-04-18 17:12:01

标签: postgresql window-functions

我可以通过查询找到总数:

with sub_total as (
select 
 *,
 sum( qty*price ) OVER( PARTITION BY invoice_id, group_id )      AS order_cost
from invoice
)

-- Here how I get is expected result:
select *,
  (SELECT sum(x) from (SELECT sum( DISTINCT order_cost ) AS x FROM sub_total sub_i GROUP BY invoice_id, group_id) t) as total_cost
from sub_total;

是否可以通过窗口函数找到这四个数字中的sum

enter image description here

我想这应该可以,但不幸的是没有:

sum( DISTINCT order_cost ) OVER ( PARTITION BY invoice_id, group_id ORDER BY group_id RANGE unbound preceeding and unbound following )

这里是fiddle

1 个答案:

答案 0 :(得分:0)

如果我了解问题所在,则需要一列具有总价值的列。

SELECT *,
      qty*price,
      SUM(qty*price) OVER (),
      SUM(qty*price) OVER (PARTITION BY invoice_id ORDER BY group_id)
 FROM invoice

这将输出:

enter image description here

相关问题