QuestionQ98

VerifiedAnalyzing Queries

A data analyst has a sales table containing the columns product_id, sale_date, and sale_amount. The analyst needs to calculate total sales for each product on each day, returning exactly one row for every product/day.

They initially use the following SQL query:

SELECT product_id, sale_date, sale_amount,  
SUM(sale_amount) OVER (PARTITION BY product_id ORDER BY sale_date) AS daily_total  
FROM sales  
ORDER BY product_id, sale_date;  

However, it returns multiple rows for the same product and date rather than a single aggregated row for each product/date combination.

Which corrected SQL query returns exactly one row per product per day, with that day’s total sales?

Explanation

A query-level GROUP BY product_id, sale_date creates one group for every product/date combination, and SUM(sale_amount) computes the total across the sales rows in that group. In contrast, a window aggregate operates across related rows while keeping the individual rows in the result set. PostgreSQL SELECT documentation PostgreSQL window-function documentation

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!