将PostgreSQL运行总结果分组

时间:2018-10-31 20:18:08

标签: sql postgresql

我正在尝试获取2家商店的总营业额。我所拥有的查询将两个商店的运行总计汇总在一起。如何更改查询以分别获取每个商店的运行总计?以下是我的查询。可以找到数据库here

select store_id,amount, sum(amount) over (order by rental_date)
from payment
join rental on payment.rental_id=rental.rental_id
join store  on payment.customer_id=store.store_id

这是我得到的结果:

store id       amont      sum
1              5.99       5.99 
1              0.99       6.98 
1              9.99       16.97 
1              4.99       21.96 
2              2.99       24.95 
1              4.99       29.94 
1              0.99       30.93 
1              3.99       34.92 

2 个答案:

答案 0 :(得分:1)

中使用partition by store_id
sum(amount) over (partition by store_id order by store_id, rental_date)

答案 1 :(得分:0)

如果您希望它们在不同的列中,您可以这样做

select
  store_id,
  amount,
  sum(case when store_id = 1 then amount else 0 end) over (order by rental_date) as store1_sum,
  sum(case when store_id = 2 then amount else 0 end) over (order by rental_date) as store2_sum,
from payment
join rental on payment.rental_id=rental.rental_id
join store  on payment.customer_id=store.store_id

对于不同的行,您可以将其分区为@BarbarosÖzhan

相关问题