Skip to main content

Use case

For a dataset that contains a sequence of changes to a property over time, we want to be able to get the most recent state of said property at any given date. In this recipe, we’ll learn how to calculate snapshots of statuses at any given date for a cube with Product Id, Status, and Changed At dimensions.
We can consider the status property to be a slowly changing dimension (SCD) of type 2. Modeling data with slowly changing dimensions is an essential part of the data engineering skillset.

Data modeling

Let’s explore the statuses cube that contains data like this:
order_idstatuschanged_at
1shipped2019-01-19 00:00:00
1processing2019-03-14 00:00:00
1completed2019-01-25 00:00:00
2processing2019-08-21 00:00:00
2completed2019-04-13 00:00:00
2shipped2019-03-18 00:00:00
We can see that statuses change occasionally. How do we count orders that remained in the shipped status at a particular date? First, we need to generate a range with all dates of interest, from the earliest to the latest. Second, we need to join the dates with the statuses and leave only the most recent statuses to date.
To generate a range of dates, here we use the GENERATE_SERIES function which is Postgres-specific. Other databases have similar functions, e.g., GENERATE_DATE_ARRAY in BigQuery.
Please note that it makes sense to make the status_snapshots cube extend the original statuses cube in order to reuse the dimension definitions. We only need to add a new dimension that indicates the date of a snapshot. We’re also referencing the definition of the statuses cube with the sql() property.

Result

To count orders that remained in the shipped status at a particular date, filter on both status_snapshots.date and status_snapshots.status. Running the same query for two different dates shows how the snapshot changes over time:
datestatuscount
2019-04-01shipped16
2019-05-01shipped25