Window functions

A Window function refers to an aggregate function that operates on a sliding window of data that is being processed as part of a SELECT query. Window functions make it possible to do things like:

  1. Perform aggregations against subsets of a result-set.
  2. Calculate a running total.
  3. Rank results.
  4. Compare a row value to a value in the preceding (or succeeding!) row(s).

peewee comes with support for SQL window functions, which can be created by calling Function.over() and passing in your partitioning or ordering parameters.

For the following examples, we’ll use the following model and sample data:

  1. class Sample(Model):
  2. counter = IntegerField()
  3. value = FloatField()
  4. data = [(1, 10),
  5. (1, 20),
  6. (2, 1),
  7. (2, 3),
  8. (3, 100)]
  9. Sample.insert_many(data, fields=[Sample.counter, Sample.value]).execute()

Our sample table now contains:

idcountervalue
1110.0
2120.0
321.0
423.0
53100.0

Ordered Windows

Let’s calculate a running sum of the value field. In order for it to be a “running” sum, we need it to be ordered, so we’ll order with respect to the Sample’s id field:

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).over(order_by=[Sample.id]).alias('total'))
  5. for sample in query:
  6. print(sample.counter, sample.value, sample.total)
  7. # 1 10. 10.
  8. # 1 20. 30.
  9. # 2 1. 31.
  10. # 2 3. 34.
  11. # 3 100 134.

For another example, we’ll calculate the difference between the current value and the previous value, when ordered by the id:

  1. difference = Sample.value - fn.LAG(Sample.value, 1).over(order_by=[Sample.id])
  2. query = Sample.select(
  3. Sample.counter,
  4. Sample.value,
  5. difference.alias('diff'))
  6. for sample in query:
  7. print(sample.counter, sample.value, sample.diff)
  8. # 1 10. NULL
  9. # 1 20. 10. -- (20 - 10)
  10. # 2 1. -19. -- (1 - 20)
  11. # 2 3. 2. -- (3 - 1)
  12. # 3 100 97. -- (100 - 3)

Partitioned Windows

Let’s calculate the average value for each distinct “counter” value. Notice that there are three possible values for the counter field (1, 2, and 3). We can do this by calculating the AVG() of the value column over a window that is partitioned depending on the counter field:

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.AVG(Sample.value).over(partition_by=[Sample.counter]).alias('cavg'))
  5. for sample in query:
  6. print(sample.counter, sample.value, sample.cavg)
  7. # 1 10. 15.
  8. # 1 20. 15.
  9. # 2 1. 2.
  10. # 2 3. 2.
  11. # 3 100 100.

We can use ordering within partitions by specifying both the order_by and partition_by parameters. For an example, let’s rank the samples by value within each distinct counter group.

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.RANK().over(
  5. order_by=[Sample.value],
  6. partition_by=[Sample.counter]).alias('rank'))
  7. for sample in query:
  8. print(sample.counter, sample.value, sample.rank)
  9. # 1 10. 1
  10. # 1 20. 2
  11. # 2 1. 1
  12. # 2 3. 2
  13. # 3 100 1

Bounded windows

By default, window functions are evaluated using an unbounded preceding start for the window, and the current row as the end. We can change the bounds of the window our aggregate functions operate on by specifying a start and/or end in the call to Function.over(). Additionally, Peewee comes with helper-methods on the Window object for generating the appropriate boundary references:

  • Window.CURRENT_ROW - attribute that references the current row.
  • Window.preceding() - specify number of row(s) preceding, or omit number to indicate all preceding rows.
  • Window.following() - specify number of row(s) following, or omit number to indicate all following rows.

To examine how boundaries work, we’ll calculate a running total of the value column, ordered with respect to id, but we’ll only look the running total of the current row and it’s two preceding rows:

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).over(
  5. order_by=[Sample.id],
  6. start=Window.preceding(2),
  7. end=Window.CURRENT_ROW).alias('rsum'))
  8. for sample in query:
  9. print(sample.counter, sample.value, sample.rsum)
  10. # 1 10. 10.
  11. # 1 20. 30. -- (20 + 10)
  12. # 2 1. 31. -- (1 + 20 + 10)
  13. # 2 3. 24. -- (3 + 1 + 20)
  14. # 3 100 104. -- (100 + 3 + 1)

Note

Technically we did not need to specify the end=Window.CURRENT because that is the default. It was shown in the example for demonstration.

Let’s look at another example. In this example we will calculate the “opposite” of a running total, in which the total sum of all values is decreased by the value of the samples, ordered by id. To accomplish this, we’ll calculate the sum from the current row to the last row.

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).over(
  5. order_by=[Sample.id],
  6. start=Window.CURRENT_ROW,
  7. end=Window.following()).alias('rsum'))
  8. # 1 10. 134. -- (10 + 20 + 1 + 3 + 100)
  9. # 1 20. 124. -- (20 + 1 + 3 + 100)
  10. # 2 1. 104. -- (1 + 3 + 100)
  11. # 2 3. 103. -- (3 + 100)
  12. # 3 100 100. -- (100)

Filtered Aggregates

Aggregate functions may also support filter functions (Postgres and Sqlite 3.25+), which get translated into a FILTER (WHERE...) clause. Filter expressions are added to an aggregate function with the Function.filter() method.

For an example, we will calculate the running sum of the value field with respect to the id, but we will filter-out any samples whose counter=2.

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).filter(Sample.counter != 2).over(
  5. order_by=[Sample.id]).alias('csum'))
  6. for sample in query:
  7. print(sample.counter, sample.value, sample.csum)
  8. # 1 10. 10.
  9. # 1 20. 30.
  10. # 2 1. 30.
  11. # 2 3. 30.
  12. # 3 100 130.

Note

The call to filter() must precede the call to over().

Reusing Window Definitions

If you intend to use the same window definition for multiple aggregates, you can create a Window object. The Window object takes the same parameters as Function.over(), and can be passed to the over() method in-place of the individual parameters.

Here we’ll declare a single window, ordered with respect to the sample id, and call several window functions using that window definition:

  1. win = Window(order_by=[Sample.id])
  2. query = Sample.select(
  3. Sample.counter,
  4. Sample.value,
  5. fn.LEAD(Sample.value).over(win),
  6. fn.LAG(Sample.value).over(win),
  7. fn.SUM(Sample.value).over(win)
  8. ).window(win) # Include our window definition in query.
  9. for row in query.tuples():
  10. print(row)
  11. # counter value lead() lag() sum()
  12. # 1 10. 20. NULL 10.
  13. # 1 20. 1. 10. 30.
  14. # 2 1. 3. 20. 31.
  15. # 2 3. 100. 1. 34.
  16. # 3 100. NULL 3. 134.

Multiple window definitions

In the previous example, we saw how to declare a Window definition and re-use it for multiple different aggregations. You can include as many window definitions as you need in your queries, but it is necessary to ensure each window has a unique alias:

  1. w1 = Window(order_by=[Sample.id]).alias('w1')
  2. w2 = Window(partition_by=[Sample.counter]).alias('w2')
  3. query = Sample.select(
  4. Sample.counter,
  5. Sample.value,
  6. fn.SUM(Sample.value).over(w1).alias('rsum'), # Running total.
  7. fn.AVG(Sample.value).over(w2).alias('cavg') # Avg per category.
  8. ).window(w1, w2) # Include our window definitions.
  9. for sample in query:
  10. print(sample.counter, sample.value, sample.rsum, sample.cavg)
  11. # counter value rsum cavg
  12. # 1 10. 10. 15.
  13. # 1 20. 30. 15.
  14. # 2 1. 31. 2.
  15. # 2 3. 34. 2.
  16. # 3 100 134. 100.

Similarly, if you have multiple window definitions that share similar definitions, it is possible to extend a previously-defined window definition. For example, here we will be partitioning the data-set by the counter value, so we’ll be doing our aggregations with respect to the counter. Then we’ll define a second window that extends this partitioning, and adds an ordering clause:

  1. w1 = Window(partition_by=[Sample.counter]).alias('w1')
  2. # By extending w1, this window definition will also be partitioned
  3. # by "counter".
  4. w2 = Window(extends=w1, order_by=[Sample.value.desc()]).alias('w2')
  5. query = (Sample
  6. .select(Sample.counter, Sample.value,
  7. fn.SUM(Sample.value).over(w1).alias('group_sum'),
  8. fn.RANK().over(w2).alias('revrank'))
  9. .window(w1, w2)
  10. .order_by(Sample.id))
  11. for sample in query:
  12. print(sample.counter, sample.value, sample.group_sum, sample.revrank)
  13. # counter value group_sum revrank
  14. # 1 10. 30. 2
  15. # 1 20. 30. 1
  16. # 2 1. 4. 2
  17. # 2 3. 4. 1
  18. # 3 100. 100. 1

Frame types: RANGE vs ROWS vs GROUPS

Depending on the frame type, the database will process ordered groups differently. Let’s create two additional Sample rows to visualize the difference:

  1. >>> Sample.create(counter=1, value=20.)
  2. <Sample 6>
  3. >>> Sample.create(counter=2, value=1.)
  4. <Sample 7>

Our table now contains:

idcountervalue
1110.0
2120.0
321.0
423.0
53100.0
6120.0
721.0

Let’s examine the difference by calculating a “running sum” of the samples, ordered with respect to the counter and value fields. To specify the frame type, we can use either:

The behavior of RANGE, when there are logical duplicates, may lead to unexpected results:

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).over(
  5. order_by=[Sample.counter, Sample.value],
  6. frame_type=Window.RANGE).alias('rsum'))
  7. for sample in query.order_by(Sample.counter, Sample.value):
  8. print(sample.counter, sample.value, sample.rsum)
  9. # counter value rsum
  10. # 1 10. 10.
  11. # 1 20. 50.
  12. # 1 20. 50.
  13. # 2 1. 52.
  14. # 2 1. 52.
  15. # 2 3. 55.
  16. # 3 100 155.

With the inclusion of the new rows we now have some rows that have duplicate category and value values. The RANGE frame type causes these duplicates to be evaluated together rather than separately.

The more expected result can be achieved by using ROWS as the frame-type:

  1. query = Sample.select(
  2. Sample.counter,
  3. Sample.value,
  4. fn.SUM(Sample.value).over(
  5. order_by=[Sample.counter, Sample.value],
  6. frame_type=Window.ROWS).alias('rsum'))
  7. for sample in query.order_by(Sample.counter, Sample.value):
  8. print(sample.counter, sample.value, sample.rsum)
  9. # counter value rsum
  10. # 1 10. 10.
  11. # 1 20. 30.
  12. # 1 20. 50.
  13. # 2 1. 51.
  14. # 2 1. 52.
  15. # 2 3. 55.
  16. # 3 100 155.

Peewee uses these rules for determining what frame-type to use:

  • If the user specifies a frame_type, that frame type will be used.
  • If start and/or end boundaries are specified Peewee will default to using ROWS.
  • If the user did not specify frame type or start/end boundaries, Peewee will use the database default, which is RANGE.

The Window.GROUPS frame type looks at the window range specification in terms of groups of rows, based on the ordering term(s). Using GROUPS, we can define the frame so it covers distinct groupings of rows. Let’s look at an example:

  1. query = (Sample
  2. .select(Sample.counter, Sample.value,
  3. fn.SUM(Sample.value).over(
  4. order_by=[Sample.counter, Sample.value],
  5. frame_type=Window.GROUPS,
  6. start=Window.preceding(1)).alias('gsum'))
  7. .order_by(Sample.counter, Sample.value))
  8. for sample in query:
  9. print(sample.counter, sample.value, sample.gsum)
  10. # counter value gsum
  11. # 1 10 10
  12. # 1 20 50
  13. # 1 20 50 (10) + (20+0)
  14. # 2 1 42
  15. # 2 1 42 (20+20) + (1+1)
  16. # 2 3 5 (1+1) + 3
  17. # 3 100 103 (3) + 100

As you can hopefully infer, the window is grouped by its ordering term, which is (counter, value). We are looking at a window that extends between one previous group and the current group.

Note

For information about the window function APIs, see:

For general information on window functions, read the postgres window functions tutorial

Additionally, the postgres docs and the sqlite docs contain a lot of good information.