In SQL, the GROUP BY clause is a powerful tool used to
organize identical data into groups based on one or more
columns. It shines when paired with aggregate functions like
SUM(), AVG(), COUNT(), MAX(), and MIN() to perform
calculations on grouped data.
Key Points About GROUP BY:
Groups Data: It organizes rows with the same values into
groups.
Works with Aggregates: It’s used alongside aggregate
functions to calculate metrics for each group (e.g., totals,
averages).
Mandatory with Aggregates: If you include both aggregate
functions and normal columns in your SELECT statement,
you must use GROUP BY.
Example: Sales Data Analysis
Imagine a Sales table:
Sale_ID Customer_ID Amount Country
1 101 100 USA
2 102 200 USA
3 101 150 Canada
4 103 300 USA
5 104 250 Canada