Skip to main content

Use case

Sometimes, there’s a need to calculate a double aggregation over a fact table. For example, if you have a line_items table that has store_id, order_id, and sales columns, you might wonder what is the median of sales per product for each store. With an ad-hoc SQL query, this double aggregation would probably be expressed as follows:

Data modeling

In Cube, measures are used to define aggregates. However, a single measure can only contain a single aggregation, e.g., SUM, APPROX_COUNT_DISTINCT, or PERCENTILE_CONT. If you’d like to define a double aggregation, e.g., a median of a sum of values, the outer aggregation would need to be defined in a separate cube and the inner aggregation (measure) would need to be brought to that cube as a subquery dimension. Also, these cubes would need to have a join definition between them. Consider the following data model:
As you can see, the sum of sales for per store and per product is defined in the nested_agg_sales cube as the sales measure. Then, it is brought to the nested_agg_stores_orders cube as sales_sum that is defined as a subquery dimension. Also, a join is defined between both cubes. Then, the median of sales is defined as the median_sales measure in the nested_agg_stores_orders cube. It’s OK to reference sales_sum in this measure because now it’s a dimension; referencing a measure from another cube here would not work.

Result

Querying the median_sales measure would give the expected result:
We can verify that it’s correct by adding one more dimension to the query: