Search⌘ K
AI Features

Answer: The GROUP BY Clause and the SUM Function

Explore how to group data using the SQL GROUP BY clause combined with the SUM aggregate function. Learn to create queries that calculate totals based on categories, use aliases, and understand alternate methods like subqueries. This lesson helps you develop essential skills to solve common SQL interview problems involving data aggregation and grouping.

Solution

The solution is given below:

MySQL
/* The query to find the total price of products for each category */
SELECT Category, SUM(Price) AS TotalPrice
FROM Products
GROUP BY Category;

Explanation

The explanation of the solution code is given below:

  • Line 2: The SELECT query selects the Category column and the total price of the Price column by calculating it using the SUM function. We use AS to set an alias for the column.

  • Line 3: The FROM clause specifies the table, Products. ...