Runnable query example at https://www.db-fiddle.com/f/ssrpQyyajYdZkkkAJBaYUp/0
I have a postgres table of sales; each row has a sale_id, product_id, salesperson, and price.
I want to write a query that returns, for each (salesperson, product_id) tuple with at least one sale:
- The total of
pricefor all of the sales made by that salesperson for that product (call thisproduct_sales). - The total of
priceover all of that salesperson's sales (call thistotal_sales).
My current query is as follows, but I feel silly writing 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:
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
WITHclause. I feel like I ought to be able to do this without a subquery orWITH.Just stumbled on this response to a different question which proposes both
sum(sum(...))and a subquery approach. Perhaps these are the best options?