簡體   English   中英

使用窗口函數編寫此 postgres 查詢時如何避免 sum(sum())?

[英]how to avoid sum(sum()) when writing this postgres query with window functions?

https://www.db-fiddle.com/f/ssrpQyyajYdZkkkAJBaYUp/0 上的可運​​行查詢示例

我有一張 postgres 銷售表; 每行都有一個sale_idproduct_idsalespersonprice

我想編寫一個查詢,為每個(salesperson, product_id)元組至少有一個銷售返回:

  • 該銷售人員對該產品進行的所有銷售的總price (稱為product_sales )。
  • 該銷售人員的所有銷售額的總price (稱為total_sales )。

我目前的查詢如下,但我覺得寫sum(sum(price))很傻。 有沒有更標准/慣用的方法?

select 
  salesperson,
  product_id,
  sum(price) as product_sales,
  sum(sum(price)) over (partition by salesperson) as total_sales
from sales
group by 1, 2
order by 1, 2

寫入sum(price)而不是sum(sum(price))產生以下錯誤:

column "sales.price" must appear in the GROUP BY clause or be used in an aggregate function

更新

  • 有關使用WITH子句的好方法,請參閱此響應 我覺得我應該能夠在沒有子查詢或WITH情況下做到這一點。

  • 只是偶然發現了對另一個問題的回答,該問題提出了sum(sum(...))和子查詢方法。 也許這些是最好的選擇?

您可以使用公用表表達式來簡化查詢並分兩步完成。

例如:

with 
s as (
  select 
    salesperson,
    product_id,
    sum(price) as product_sales
  from sales
  group by salesperson, product_id
)
select
  salesperson, 
  product_id,
  product_sales,
  sum(product_sales) over (partition by salesperson) as total_sales
from s
order by salesperson, product_id

結果:

 salesperson  product_id  product_sales  total_sales 
 ------------ ----------- -------------- ----------- 
 Alice        1           2000           5400        
 Alice        2           2200           5400        
 Alice        3           1200           5400        
 Bobby        1           2000           4300        
 Bobby        2           1100           4300        
 Bobby        3           1200           4300        
 Chuck        1           2000           4300        
 Chuck        2           1100           4300        
 Chuck        3           1200           4300        

請參閱DB Fiddle 上的運行示例。

你可以試試下面的——

select * from
(
select 
  salesperson,
  product_id,
  sum(price) over(partition by salesperson,product_id) as product_sales,
  sum(price) over(partition by salesperson) as total_sales,
  row_number() over(partition by salesperson,product_id order by sale_id) as rn
from sales s
)A where rn=1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM