Overview
TheSUM()
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: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 onesParameters
expression
: input’s column or expression values to be summedPARTITION BY
: optional clause, which divides the result set into partitions to which the function is appliedROWS | RANGE BETWEEN
: range-based window frame relative to the current row
Examples
For the needs of this section, we will create thewinsales
table that stores details of some sales transactions:
SUM() with ORDER BY
In this example, we will focus on executing theSUM()
window function with ORDER BY
keyword:
SUM() with ORDER BY and ROWS Frame
In this example we will calculate the running total ofqty
ordered by dateid and salesid using a ROWS UNBOUNDED PRECEDING
frame,
which sums all rows from the start up to the current row:
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 theSUM()
function with ORDER BY
keyword and PARTITION BY
clause:
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:qty
of all sales within the 30-day window ending at the current row’s dateid
: