[英]how to avoid sum(sum()) when writing this postgres query with window functions?
Runnable query example at https://www.db-fiddle.com/f/ssrpQyyajYdZkkkAJBaYUp/0 https://www.db-fiddle.com/f/ssrpQyyajYdZkkkAJBaYUp/0 上的可运行查询示例
I have a postgres table of sales;我有一张 postgres 销售表; each row has a sale_id
, product_id
, salesperson
, and price
.每行都有一个sale_id
、 product_id
、 salesperson
和price
。
I want to write a query that returns, for each (salesperson, product_id)
tuple with at least one sale:我想编写一个查询,为每个(salesperson, product_id)
元组至少有一个销售返回:
price
for all of the sales made by that salesperson for that product (call this product_sales
).该销售人员对该产品进行的所有销售的总price
(称为product_sales
)。price
over all of that salesperson's sales (call this total_sales
).该销售人员的所有销售额的总price
(称为total_sales
)。 My current query is as follows, but I feel silly writing sum(sum(price))
.我目前的查询如下,但我觉得写sum(sum(price))
很傻。 Is there a more standard/idiomatic approach?有没有更标准/惯用的方法?
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
Writing sum(price)
instead of sum(sum(price))
yields the following error:写入sum(price)
而不是sum(sum(price))
产生以下错误:
column "sales.price" must appear in the GROUP BY clause or be used in an aggregate function
UPDATES更新
See this response for a nice approach using a WITH
clause.有关使用WITH
子句的好方法,请参阅此响应。 I feel like I ought to be able to do this without a subquery or WITH
.我觉得我应该能够在没有子查询或WITH
情况下做到这一点。
Just stumbled on this response to a different question which proposes both sum(sum(...))
and a subquery approach.只是偶然发现了对另一个问题的回答,该问题提出了sum(sum(...))
和子查询方法。 Perhaps these are the best options?也许这些是最好的选择?
You can use a Common Table Expression to simplify the query and do it in two steps.您可以使用公用表表达式来简化查询并分两步完成。
For example:例如:
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
Result:结果:
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
See running example at DB Fiddle .请参阅DB Fiddle 上的运行示例。
You can try the below -你可以试试下面的——
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.