How do you use aggregations with grouping in SQL?

Imagine you are running a popular online store, and you’d like to analyze your sales data to understand your customers’ preferences better. You have a database with a table called ‘sales,’ which contains information on each sale, including the date, product_id, and sale_amount. You might want to find the total revenue per product to gain insights. This is where a SQL GROUP BY clause with an aggregate function comes in handy!

Here’s a step-by-step guide to help you write a SQL query to achieve this: 
  1. First, decide on the columns you want to aggregate. In this case, we’re interested in the ‘product_id’ and ‘sale_amount’ columns.
  2. Choose the aggregate function that fits your needs. Since we want to calculate the total revenue per product, we’ll use the SUM() function. You could replace this with another aggregate function (e.g., AVG, COUNT, MAX, MIN, etc.) to calculate a different grouped summary metric.
  3. Write a SELECT statement that includes the columns you want to aggregate and apply the aggregate function to the ‘sale_amount’ column. We’ll also include the ‘product_id’ column, which will be used in the GROUP BY clause.
  4. Add a GROUP BY clause that specifies the column you want to group the data by. In this case, it’s the ‘product_id’ column.
Here’s an example query based on these instructions: 

Now, let’s break down the query: 
  • SELECT product_id, SUM(sale_amount) as total_revenue: This part of the query selects the ‘product_id’ column and applies the SUM() function to the ‘sale_amount’ column. We also use the ‘as‘ keyword to rename the resulting column as ‘total_revenue.’
  • FROM sales: This part specifies the table we’re working with, which is the ‘sales’ table.
  • GROUP BY product_id: The GROUP BY clause groups the data by the ‘product_id’ column, so we get the total revenue per product.

As a result, this query will provide you with a list of product_ids and their corresponding total revenues, making it easier to analyze your sales data and better understand your customers’ preferences.


Related Tags: