The SQL GROUP BY statement is used to group rows that have the same values into summary rows, often used with aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX(). It is commonly used to generate reports, summarize data, or perform calculations on grouped data.
Syntax:
SELECT column1, column2, aggregate_function(column3)
FROM table_name
WHERE condition
GROUP BY column1, column2;
Explanation:
column1, column2: The columns you want to group by.aggregate_function(column3): The aggregate function to perform on other columns (e.g.,COUNT(),SUM(),AVG(), etc.).table_name: The name of the table from which to retrieve data.WHERE condition: Optional, filters the data before applyingGROUP BY.
Example:
Consider a table sales with the following data:
| id | product | amount | sale_date |
|---|---|---|---|
| 1 | Widget A | 50 | 2024-12-01 |
| 2 | Widget B | 30 | 2024-12-01 |
| 3 | Widget A | 70 | 2024-12-02 |
| 4 | Widget A | 90 | 2024-12-02 |
| 5 | Widget B | 40 | 2024-12-03 |
If we want to find the total sales amount for each product, we can use:
SELECT product, SUM(amount) AS total_sales
FROM sales
GROUP BY product;
Result:
| product | total_sales |
|---|---|
| Widget A | 210 |
| Widget B | 70 |
Important Notes:
- Columns listed in the
SELECTclause must either be included in theGROUP BYclause or used with an aggregate function. GROUP BYgroups the results based on the distinct values of the specified columns.
Let me know if you need more details or specific examples!
No comments:
Post a Comment