Skip to main content

Overview

The SUM() window function returns the sum of the input column or expression values. It can be used with a RANGE clause, that allows you to define a logical frame of rows based on the values of the current row, rather than a fixed number of rows.

Syntax

The syntax for this function is as follows:
The expression’s argument types supported by the SUM window function are INTEGER, BIGINT, REAL and DOUBLE PRECISION. The return types of the SUM function are: BIGINT for integer and DOUBLE PRECISION for floating-point arguments.
The SUM() window function works with numeric values and ignores NULL ones

Parameters

  • expression: input’s column or expression values to be summed
  • PARTITION BY: optional clause, which divides the result set into partitions to which the function is applied
  • ROWS | RANGE BETWEEN: range-based window frame relative to the current row

Examples

For the needs of this section, we will create the winsales table that stores details of some sales transactions:

SUM() with ORDER BY

In this example, we will focus on executing the SUM() window function with ORDER BY keyword:
The output from the above query includes the sales ID, date ID, seller ID, quantity and quantity sum:

SUM() with ORDER BY and ROWS Frame

In this example we will calculate the running total of qty ordered by dateid and salesid using a ROWS UNBOUNDED PRECEDING frame, which sums all rows from the start up to the current row:
After executing the query above, we get the following output:
The running_qty_sum column shows the cumulative sum of qty ordered by dateid and salesid. For each row, it sums all qty values from the first row up to the current row in that order.

SUM() with ORDER BY and PARTITION BY

In this example we will focus on executing the SUM() function with ORDER BY keyword and PARTITION BY clause:
After executing the query above, we get the following output:

Time Series: SUM() with RANGE BETWEEN for Last 30 Days

In this example, we will demonstrate a common time series use case. Calculating the rolling sum of sales quantity over the last 30 days for each row, using the RANGE BETWEEN INTERVAL ‘30 days’ PRECEDING AND CURRENT ROW frame:
The output from the above query sums the qty of all sales within the 30-day window ending at the current row’s dateid: