Additional SQL - Aggregate Functions Cheatsheet - Codecademy
Additional SQL - Aggregate Functions Cheatsheet - Codecademy
Aggregate Functions
Column References
The GROUP BY and ORDER BY clauses can
reference the selected columns by number in which they SELECT COUNT(*) AS 'total_movies',
appear in the SELECT statement. The example query rating
will count the number of movies per rating, and will: FROM movies
GROUP BY 2
●
GROUP BY column 2 ( rating ) ORDER BY 1;
●
ORDER BY column 1 ( total_movies )
GROUP BY Clause
The GROUP BY clause will group records in a result set
by identical values in one or more columns. It is often SELECT rating,
used in combination with aggregate functions to query COUNT(*)
information of similar records. The GROUP BY clause FROM movies
can come after FROM or WHERE but must come GROUP BY rating;
/
MIN() Aggregate Function
The MIN() aggregate function returns the smallest
value in a column. For instance, to nd the smallest value SELECT MIN(amount)
of the amount column from the table named FROM transactions;
HAVING Clause
The HAVING clause is used to further lter the result
SELECT year,
set groups provided by the GROUP BY clause.
COUNT(*)
HAVING is often used with aggregate functions to lter
FROM movies
the result set groups based on an aggregate property. The
given query will select only the records (rows) from only GROUP BY year
years where more than 5 movies were released per year. HAVING COUNT(*) > 5;
ROUND() Function
The ROUND() function will round a number value to a
speci ed number of places. It takes two arguments: a SELECT year,
number, and a number of decimal places. It can be ROUND(AVG(rating), 2)
combined with other aggregate functions, as shown in the FROM movies
given query. This query will calculate the average rating of WHERE year = 2015;
movies from 2015, rounding to 2 decimal places.
Aggregate Functions
Aggregate functions perform a calculation on a set of
values and return a single value:
●
COUNT()
●
SUM()
●
MAX()
●
MIN()
●
AVG()