Calculate Percent of Total Sales Using Window Functions
📖 Scenario: You work in a retail company database. You have a table of sales data showing how much each product sold. You want to find out what percentage of the total sales each product represents.
🎯 Goal: Create a SQL query that calculates the percent of total sales for each product using window functions.
📋 What You'll Learn
Create a table called
sales with columns product (text) and amount (integer).Insert the exact sales data for 5 products: 'Apples' 100, 'Bananas' 150, 'Cherries' 50, 'Dates' 200, 'Elderberries' 100.
Write a SQL query that selects
product, amount, and a new column percent_of_total which shows the sales amount as a percentage of the total sales.Use a window function with
SUM(amount) OVER () to calculate the total sales.Format the
percent_of_total as a decimal number between 0 and 100 with two decimal places.💡 Why This Matters
🌍 Real World
Retail and sales databases often need to show how each product contributes to total sales. This helps managers understand product performance.
💼 Career
Knowing how to use window functions to calculate percentages and totals is a key skill for data analysts and database developers.
Progress0 / 4 steps