eolas/zk/Aggregate_functions_in_SQL.md

38 lines
540 B
Markdown
Raw Normal View History

2022-08-05 20:30:04 +01:00
---
2022-08-16 11:58:34 +01:00
tags: [SQL]
2022-08-05 20:30:04 +01:00
---
2022-12-13 19:08:20 +00:00
# Aggregate functions in SQL
Aggregate functions enable us to return data about the data that a table holds.
For example the sum of a given column or its average.
2022-08-05 20:30:04 +01:00
2022-08-16 11:58:34 +01:00
## Count return with custom variable
2022-08-05 20:30:04 +01:00
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:30:04 +01:00
SELECT COUNT(*) AS total_sales
FROM SALES
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:30:04 +01:00
## Sum
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:30:04 +01:00
SELECT SUM(price) as total_value
FROM sales
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:30:04 +01:00
2022-08-16 11:58:34 +01:00
## Average
2022-08-05 20:30:04 +01:00
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:30:04 +01:00
SELECT AVG(price) as average_income
FROM sales
2022-08-16 11:58:34 +01:00
```
2022-08-05 20:30:04 +01:00
## Applying aggregate function with sorting applied
2022-08-16 11:58:34 +01:00
```sql
2022-08-05 20:30:04 +01:00
SELECT COUNT(*) AS total_sales
FROM sales
GROUP BY employee_id
2022-08-16 11:58:34 +01:00
```