Menu
Coddy logo textTech

Aggregation Functions

Part of the Fundamentals section of Coddy's SQL journey — lesson 68 of 72.

Aggregation functions are used to calculate the AVG() or MAX() or any other aggregation function up until the current row.
For example, we could calculate the maximum revenue we got until each ending period:

monthrevenueregion
440East
520East
660West
755West
861East
SELECT month, revenue, MAX(revenue) OVER (ORDER BY month ASC) as max_revenue
from table1

This will return:

monthrevenuemax_revenue
44040
52040
66060
75560
86161

For months 4 and 5 the maximum revenue is 40, for months 5 and 6 the revenue is 60 and for months 8, it is 61. This is because when it finds a new bigger revenue, it drops the old one and uses the biggest so far.

For AVG() function it will look like this:

SELECT month, revenue, AVG(revenue) OVER (ORDER BY month ASC) as avg_revenue
from table1
monthrevenueavg_revenue
44040
52030
66040
75543.75
86147.2

We can also group our calculations by specific categories using PARTITION BY. For example:

SELECT month, revenue, region,
MAX(revenue) OVER (PARTITION BY region ORDER BY month ASC) as max_revenue
FROM table1

Would give us:

monthrevenueregionmax_revenue
440East40
520East40
660West60
755West60
861East61

Now the maximum is calculated separately for each region. The East region and West region maintain their own running maximums independently.

challenge icon

Challenge

Easy

Available tables and columns:

  • <strong>books</strong>: <strong>book</strong>, <strong>page</strong>, <strong>words</strong>

For each book, display the book name, its total pages, the number of words on each page, and calculate:

  1. The maximum number of words found on any page in that book
  2. The average number of words per page for the entire book
  3. The difference between the current page's words and the book's average words per page

Display the results ordered by book and page number.

Return the following columns:

  • book
  • page
  • words
  • max_words_in_book
  • avg_words_per_page
  • diff_from_avg

Cheat sheet

Window functions with aggregation calculate values across a set of rows related to the current row. Use OVER clause with ORDER BY for running calculations:

SELECT column, 
       MAX(column) OVER (ORDER BY column ASC) as running_max,
       AVG(column) OVER (ORDER BY column ASC) as running_avg
FROM table

Use PARTITION BY to group calculations by categories:

SELECT column, category,
       MAX(column) OVER (PARTITION BY category ORDER BY column ASC) as max_per_category
FROM table

This calculates the maximum separately for each category, maintaining independent running calculations.

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals