2.8 KiB
2.8 KiB
- #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.,
+
,-
,*
,/
.
- Aggregate Functions are only supported in
-
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:: 3GROUP BY
#cardGROUP 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
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:: 5GROUP BY
#card- 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.
- The
- ^^Important: You must
GROUP BY
all attributes in theSELECT
clause unless they are involved in an aggregation.^^- This ^^wouldn't work^^ as we do not
GROUP BY
all the attributes in theSELECT
clause -salary
remains ungrouped.-
SELECT dno, salary FROM employee GROUP BY dno -- THIS IS WRONG
-
- This ^^wouldn't work^^ as we do not
-
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:: 1HAVING
#cardHAVING <group condition>
- The
HAVING
clause is used in conjunction withGROUP BY
and allows the specification of conditions on groups. - The column names in the
HAVING
clause must also appear in theGROUP BY
list or be contained within an aggregate function, i.e., you cannot apply aHAVING
condition to something that has not been calculated already.
- The