Complete the code to calculate the total sales per product using GROUP BY.
SELECT product_id, SUM(sales) AS total_sales FROM sales_data GROUP BY [1];The GROUP BY clause groups rows by the specified column. Here, grouping by product_id allows us to sum sales per product.
Complete the code to calculate the running total of sales per product using a window function.
SELECT product_id, sales, SUM(sales) OVER (PARTITION BY [1] ORDER BY date) AS running_total FROM sales_data;The PARTITION BY clause divides the data into groups. Here, partitioning by product_id calculates running totals per product.
Fix the error in the query to calculate average sales per product using GROUP BY.
SELECT product_id, AVG(sales) FROM sales_data WHERE sales > 0 GROUP BY [1];
The GROUP BY clause must include the column used to group the results. Here, product_id is correct.
Fill both blanks to calculate the rank of sales per product ordered by date.
SELECT product_id, sales, RANK() OVER (PARTITION BY [1] ORDER BY [2]) AS sales_rank FROM sales_data;
Partitioning by product_id groups the data per product. Ordering by date ranks sales chronologically.
Fill all three blanks to create a query that shows total sales per product and each sale's percentage of that total.
SELECT product_id, sales, SUM(sales) OVER (PARTITION BY [1]) AS total_sales, ROUND(sales * 100.0 / [2], 2) AS sales_percent FROM sales_data;
Partition by product_id to get total sales per product. Use the window function SUM(sales) OVER (PARTITION BY product_id) to get total_sales. Then calculate the percentage by dividing sales by total_sales.