55 lines
2.8 KiB
Markdown
55 lines
2.8 KiB
Markdown
- #[[CT230 - Database Systems I]]
|
|
- **Previous Topic:** [[SQL SELECT: Working with Strings & Subqueries]]
|
|
- **Next Topic:** [[Entity Relationship Models]]
|
|
- **Relevant Slides:** 
|
|
-
|
|
- # Aggregate Functions #card
|
|
card-last-interval:: -1
|
|
card-repeats:: 1
|
|
card-ease-factor:: 2.46
|
|
card-next-schedule:: 2022-11-15T00:00:00.000Z
|
|
card-last-reviewed:: 2022-11-14T16:29:15.913Z
|
|
card-last-score:: 1
|
|
- **Aggregate Functions** are only supported in `SELECT` clauses & `HAVING` clauses.
|
|
- Keywords `SUM`, `AVG`, `MIN`, `MAX` work as expected and can only be applied to **numeric** data.
|
|
- Keyword `COUNT` can be used to count the number of tuples / values / rows specified in a query.
|
|
- We can also use mathematical operations as part of an aggregate function on **numeric** data, e.g., `+`, `-`, `*`, `/`.
|
|
- # `GROUP BY` #card
|
|
card-last-interval:: 4
|
|
card-repeats:: 2
|
|
card-ease-factor:: 2.32
|
|
card-next-schedule:: 2022-11-27T12:18:53.349Z
|
|
card-last-reviewed:: 2022-11-23T12:18:53.350Z
|
|
card-last-score:: 3
|
|
- `GROUP BY <group attributes>`
|
|
- The `GROUP BY` clause allows the grouping of rows of a table together so that all occurrences within a specified group are collected together.
|
|
- Aggregate clauses can then be applied to groups.
|
|
- ## Using Aggregate Functions with `GROUP BY` #card
|
|
card-last-interval:: 4.14
|
|
card-repeats:: 2
|
|
card-ease-factor:: 2.56
|
|
card-next-schedule:: 2022-11-27T15:17:10.883Z
|
|
card-last-reviewed:: 2022-11-23T12:17:10.883Z
|
|
card-last-score:: 5
|
|
- The `GROUP BY` clause specifies the group and the aggregate function is applied to the group.
|
|
- `COUNT(*)` can be used to *count* the number of rows (tuples) in the specified groups.
|
|
- `SUM`, `AVG`, `MIN`, `MAX` can be used to find the sum, average, min, & max of a *numerical value* in a specified group.
|
|
- ^^**Important:** You must `GROUP BY` **all** attributes in the `SELECT` clause *unless* they are involved in an aggregation.^^
|
|
- This **^^wouldn't work^^** as we do not `GROUP BY` all the attributes in the `SELECT` clause - `salary` remains ungrouped.
|
|
- ```SQL
|
|
SELECT dno, salary
|
|
FROM employee
|
|
GROUP BY dno -- THIS IS WRONG
|
|
```
|
|
-
|
|
- # `HAVING` #card
|
|
card-last-interval:: -1
|
|
card-repeats:: 1
|
|
card-ease-factor:: 2.36
|
|
card-next-schedule:: 2022-11-18T00:00:00.000Z
|
|
card-last-reviewed:: 2022-11-17T20:18:23.927Z
|
|
card-last-score:: 1
|
|
- `HAVING <group condition>`
|
|
- The `HAVING` clause is used in conjunction with `GROUP BY` and allows the specification of **conditions on groups**.
|
|
- The column names in the `HAVING` clause must also appear in the `GROUP BY` list or be contained within an aggregate function, i.e., you cannot apply a `HAVING` condition to something that has not been calculated already.
|
|
- |