sumSimpleState
Description
The SimpleState
combinator can be applied to the sum
function to return the sum across all input values. It returns the result with
type SimpleAggregateState
.
Example Usage
Tracking upvotes and downvotes
Let's look at a practical example using a table that tracks votes on posts.
For each post, we want to maintain running totals of upvotes, downvotes, and an
overall score. Using the SimpleAggregateFunction
type with sum is suited for
this use case as we only need to store the running totals, not the entire state
of the aggregation.
Create a materialized view with SimpleAggregateFunction
type columns:
Insert sample data:
Query the Materialized View using the SimpleState
combinator:
Note that we could get the same result using just sum
instead of sumSimpleState
:
When you use sumSimpleState(column)
:
- It directly extracts the stored sum value without doing any additional aggregation.
- The result is of type
SimpleAggregateFunction(sum, Int64)
When you use sum(column)
on a SimpleAggregateFunction
column:
- ClickHouse recognizes this special case and implicitly converts it to behave
like
sumSimpleState
- The result is
Int64