The COUNT()
window function allows you to retrieve the number of records that meet a specific criteria. When using it with he RANGE
clause, it allows you to perform counts within a defined range based on the values of the current row.
This function can be used with all data types supported by Oxla.
There are two available variants of that function:
COUNT(*)
: counts all rows in the target table, regardless of whether they contain NULL values or notCOUNT(expression)
: counts the number of non-NULL values in a specific column or expressionThe syntax for this function is as follows:
The COUNT()
window function always return BIGINT
as an output, which represents the total number of rows in a table irrespective of the input types.
expression
: input’s column or expression that the function operates onPARTITION 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 rowFor the needs of this section, we will create a winsales
table that stores the details of some sales transactions:
In this example, we will focus on executing the variant of this function that counts all rows in the target table:
The output of the code abote displays the sales ID, quantity and the count of all rows from the start of the data window:
In this example, we will focus on executing the variant of this function that counts the number of non-NULL values in a specific expression:
Here is the output for the query presented above:
In this example, we will demonstrate counting the number of sales within a 90-day window prior to each sale, based on dateid
:
This query above counts the number of sales transactions within a 90-day window before each dateid
,
including the current sale: