Grouping data with GROUP BY

Using GROUP BY in SQL

Consider a scenario. You have a listing. This listing comprises all your requests from a web-based shop. The listing involves details. Details like the request date and entire sum. Also details like the item classification. Items such as electronics, garments and books.

Subsequently you wish to compute how much was used on every item grouping. This is instance when you require GROUP BY.

What is the function of GROUP BY? It breaks down your facts into clusters. It relies on a specialized type of column. It employs functions. Functions similar to SUM, COUNT and AVG.

To elaborate. Imagine you wanted to tally the overall sales for each item grouping. Your order data mirrors this:

Order Date Total Amount Product Category
2024-01-01 100 Electronics
2024-01-05 50 Clothing
2024-01-10 200 Electronics
2024-01-15 80 Clothing
2024-01-20 150 Books

To derive the total sales for every product category. The SQL query is needed. It is as follows:

SELECT ProductCategory, SUM(TotalAmount) AS TotalSales
FROM Orders
GROUP BY ProductCategory;

This particular query yields a result:

ProductCategory TotalSales
Electronics 300
Clothing 130
Books 150

Explanation:

  • SELECT ProductCategory, SUM(TotalAmount) AS TotalSales: Here we see a query. This query conveys the data you want. You are interested in product category. The total sum for every category too.
  • FROM Orders: This part of the query identifies a table. Data is being extracted from this table.
  • GROUP BY ProductCategory: Here the clause is present. This clause tells the database to group data. The group is based on 'ProductCategory'.
  • AS TotalSales: This clause is present as well. It assigns a name to the sum that was calculated. The total sales value is now labeled as "TotalSales". The readability improves with this label.

So, clause is helpful. It categorizes your orders. Orders are categorized by product category. The clause also calculates total sales. The total sales value is calculated for each category.