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.SELECT 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.
SELECT year,
month,
COUNT(*) AS count
FROM tutorial.storesales
GROUP BY year, month
ORDER BY month, yearFiltering
What if we are only interested in the months when the highest price is over 200.
SELECT year,
month,
MAX(price) AS month_high
FROM tutorial.storesales
GROUP BY year, month
HAVING MAX(price) > 200
ORDER BY year, month
---- Equivalent Query ----
SELECT *
FROM (
SELECT year,
month,
MAX(price) AS month_high
FROM tutorial.storesales
GROUP BY year, month
) sub
WHERE month_high > 200
ORDER BY year, month- Using the aggregate function and the
HAVINGclause at one time to filter on an aggregated column. - The
WHEREclause does not work in this case.