🚀 Launch Week is coming June 23-27.
Get updates.
Back

Clickhouse Tips #1: Calculating Aggregations After a Given Date

Tips and recipes to learn how to make the most of ClickHouse, curated weekly by the Tinybird team.
Javier Santana
Javier SantanaCo-founder

Imagine you have a table like

And you want to calculate, per day, the sum(amount) of previous and following days.

For example, for the day 2020-01-05 you have to calculate sumIf(amount, ts < '2020-01-05') and sumIf(amount, ts >= '2020-01-05')

I think there are many ways to do it but this works:

Start building with Tinybird!
If you've read this far, you might want to use Tinybird as your analytics backend. You can just get started, on the free plan.
Sign up

Check out this snapshot for a step-by-step explanation of what’s going on here.

I think a way to exploit that values for each day don’t need to be calculated every time for each day using a nice function, arrayCumSum, plus some other array magic.

Check this out for a step-by-step explanation.

I feel there should be an easier way but that’s just a feeling.

Subscribe to our newsletter
Get 10 links weekly to the Data and AI articles the Tinybird team is reading.
Do you like this post? Spread it!

Related posts

1ClickHouse tips #5: Adding and subtracting intervals
1ClickHouse tips #2: Debugging ClickHouse on Visual Studio Code
1ClickHouse tips #3: the transform function
1ClickHouse tips #6: Filtering data in subqueries to avoid joins
1ClickHouse tips #8: Generating time-series on ClickHouse
1ClickHouse tips #11: Best way to get query types
1ClickHouse tips #9: Filling gaps in time-series on ClickHouse
1ClickHouse tips #7: Forward and backfilling null values

Skip the infra work. Ship your first API today.

Read the docs
Tinybird wordmark
Tinybird uses cookies and similar tech to enhance site navigation, analyze site usage and traffic, and as further described in our Privacy Notice. Click "Allow All" to enable all cookies or "Reject All" to reject them. You can also set your preferences by clicking "Manage cookies".