Week 7 - Day 1-4 - Grouping Data With GROUP by
Week 7 - Day 1-4 - Grouping Data With GROUP by
It is
often used in combination with aggregate functions to summarize and analyze data. Here's a detailed
explanation of how to use the `GROUP BY` clause and aggregate functions like `SUM`, `AVG`, `COUNT`,
`MIN`, and `MAX` in SQL:
```sql
SELECT column1, column2, aggregate_function(column3)
FROM table
GROUP BY column1, column2;
```
- `SELECT` specifies the columns you want to retrieve, including the aggregate functions.
- `FROM` specifies the table from which you're retrieving data.
- `GROUP BY` specifies the columns by which you want to group the data.
```sql
SELECT Category, SUM(SalesAmount)
FROM Sales
GROUP BY Category;
```
In this example, we're selecting the "Category" column and calculating the total sales amount for each
category.
```sql
SELECT Category, SUM(SalesAmount)
FROM Sales
GROUP BY Category
HAVING SUM(SalesAmount) > 10000;
```
In this example, we're only selecting categories with a total sales amount greater than 10,000.
```sql
SELECT Category, YEAR(SaleDate) AS SaleYear, SUM(SalesAmount)
FROM Sales
GROUP BY Category, SaleYear;
```
In this example, we're creating groups based on both the product category and the year of the sale.
**Using Aliases:**
You can use column aliases to make your query results more readable. For example:
```sql
SELECT Category, SUM(SalesAmount) AS TotalSales
FROM Sales
GROUP BY Category;
```
In this example, we're providing an alias "TotalSales" for the result of the `SUM(SalesAmount)`
function.
In summary, the `GROUP BY` clause in SQL is used to group rows based on one or more columns, and
it is typically used in combination with aggregate functions to summarize data within those groups.
Common aggregate functions like `SUM`, `AVG`, `COUNT`, `MIN`, and `MAX` allow you to perform
calculations on grouped data, providing valuable insights and summaries for data analysis. The
`HAVING` clause is used to filter the grouped data based on aggregate function results.