COUNT() OVER ...
All functions > WINDOW FUNCTION > COUNT() OVER ...
Returns the count of rows in the window frame.
Syntax
COUNT() | COUNT(DISTINCT expr) [FILTER (WHERE condition) | WITHIN (WHERE condition)] OVER ([PARTITION BY expr [, ...]] [ORDER BY sort_item [, ...]] [ROWS|RANGE|GROUPS frame])
Notes
- COUNT() counts every row in the window frame
- COUNT() takes no argument; COUNT(*) and COUNT(expr) are not valid
- To count non-NULL values, use COUNT_IF(expr IS NOT NULL) or COUNT() FILTER (WHERE expr IS NOT NULL)
- Use COUNT(DISTINCT expr) for a running count of distinct non-NULL values
- Always returns BIGINT type
- Useful for running counts and row numbering within windows
See also
Examples
FeatureQL
-- Cumulative row count (1, then 2, …), not id
-- Cumulative count counting only rows where v > 15 (10 and 5 excluded from the frame)
-- Per-row exact distinct counts (BIGINTs), not the values in v
-- Distinct count counting only rows where v > 15 (10 and 5 excluded from the frame)
RETURN
f1 := ZIP(ARRAY(1, 2, 3, 4) AS id, ARRAY(30, 10, 20, 5) AS v).TRANSFORM(
RETURN COUNT() OVER (ORDER BY id ASC)
).UNWRAP(),
f2 := ZIP(ARRAY(1, 2, 3, 4) AS id, ARRAY(30, 10, 20, 5) AS v).TRANSFORM(
RETURN COUNT() FILTER (WHERE v > 15) OVER (ORDER BY id ASC)
).UNWRAP(),
f3 := ZIP(ARRAY(1, 2, 3, 4) AS id, ARRAY(30, 10, 20, 5) AS v).TRANSFORM(
RETURN COUNT(DISTINCT v) OVER (ORDER BY id ASC)
).UNWRAP(),
f4 := ZIP(ARRAY(1, 2, 3, 4) AS id, ARRAY(30, 10, 20, 5) AS v).TRANSFORM(
RETURN COUNT(DISTINCT v) FILTER (WHERE v > 15) OVER (ORDER BY id ASC)
).UNWRAP()
;Result
| f1 ARRAY<BIGINT> | f2 ARRAY<BIGINT> | f3 ARRAY<BIGINT> | f4 ARRAY<BIGINT> |
|---|---|---|---|
| [1, 2, 3, 4] | [1, 1, 2, 2] | [1, 2, 3, 4] | [1, 1, 2, 2] |