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:
COUNTcounts the number of non-NULLrows in a columnCOUNT(DISTINCT price)counts the number of the distinct non-NULLvalues inprice.
SUMadds together all the values in a numeric columnNULLis treated as0.
MINandMAXreturn the lowest and highest values in a numeric column, respectivelyAVGcalculates the average of a group of selected valuesIt can ONLY be used on numerical columns.
NULLis 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
HAVINGclause at one time to filter on an aggregated column. - The
WHEREclause does not work in this case.
View / Make Comments