SQL Patterns
SQL Grouping Data
SQL Data Grouping Patterns
Grouping with GROUP BY and HAVING, including ROLLUP, organizes data.
Understanding GROUP BY Clause
The GROUP BY clause in SQL is used to arrange identical data into groups. This is particularly helpful when you want to use aggregate functions like COUNT()
, SUM()
, AVG()
, etc., on columns to get summarized results. The GROUP BY
clause follows the WHERE
clause in a SQL statement and precedes the ORDER BY
clause.
Using HAVING Clause for Conditional Grouping
The HAVING clause is used to apply a condition to groups created by the GROUP BY
clause. This is similar to the WHERE
clause, but HAVING
is used for groups, whereas WHERE
is used for individual rows.
Advanced Grouping with ROLLUP
ROLLUP is an extension of the GROUP BY
clause that creates subtotals that roll up from the most detailed level to a grand total. This is useful for generating reports with summary rows.
Practical Example: Sales Data Analysis
Consider a table sales
with columns product_id
, sales_person
, and amount
. You can use GROUP BY
and ROLLUP
to analyze the total sales per product and per sales person, including a grand total.
This query provides a breakdown of sales for each product by each sales person and includes a total for each product and an overall total for all sales.
SQL Patterns
- Previous
- Sorting Data