When it comes to reporting some statistics by group in SQL, we will
think of using the aggregate functions and, if needed, the
WHERE
clause for filtering. However, the WHERE
clause doesn't allow you to filter on aggregate columns. To complete the
query at one time without subqueries, we need the help of the
HAVING
clause.
Aggregate Functions
There are four popular aggregate functions in SQL:
COUNT
counts the number of non-NULL
rows in a columnCOUNT(DISTINCT price)
counts the number of the distinct non-NULL
values inprice
.
SUM
adds together all the values in a numeric columnNULL
is treated as0
.
MIN
andMAX
return the lowest and highest values in a numeric column, respectivelyAVG
calculates the average of a group of selected valuesIt can ONLY be used on numerical columns.
NULL
is ignored in the calculation.1
2
3
4
5
6SELECT AVG(price)
FROM tutorial.storesales
WHERE price IS NOT NULL
---- Equivalent Query ----
SELECT AVG(price)
FROM tutorial.storesales
Aggregate by Group
For example, you might want to count the number of entries for each year and month.
1 | SELECT year, |
Filtering
What if we are only interested in the months when the highest price is over 200.
1 | SELECT year, |
- Using the aggregate function and the
HAVING
clause at one time to filter on an aggregated column. - The
WHERE
clause does not work in this case.
View / Make Comments