sqlbeginner10 minutes

Calculate Total Sales per Product Using SQL Aggregate Functions

Write an SQL query to find the total sales for each product using aggregate functions.

Challenge prompt

Given a table named Sales with columns ProductID, Quantity, and Price, write an SQL query to calculate the total sales amount (Quantity * Price) for each product. The output should include ProductID and the total sales amount labeled as TotalSales. Order the results by TotalSales in descending order.

Guidance

  • Use the SUM() aggregate function to calculate total sales per product.
  • Multiply Quantity by Price for each sale before summing.
  • Group the results by ProductID.

Hints

  • Remember to use GROUP BY when applying aggregate functions on grouped data.
  • Calculate the total sales per row by multiplying Quantity and Price inside the SUM function.

Starter code

SELECT ProductID, SUM(Quantity * Price) AS TotalSales
FROM Sales
GROUP BY ProductID
ORDER BY TotalSales DESC;

Expected output

ProductID | TotalSales ----------|----------- 101 | 5500.00 102 | 4200.00 103 | 3300.00

Core concepts

SUM()GROUP BYORDER BYAggregate Functions

Challenge a Friend

Send this duel to someone else and see if they can solve it.