Skip to main content
On this page

Kater SQL Functions Calculation context

CALCULATE_BY

Works a measure out at exactly the dimensions you name, then combines those values for each row.

Family: Calculation context

Use it for an average per customer across the whole business.

Syntax

CALCULATE_BY(measure, dimension, ..., summarize => 'avg' | 'sum' | 'min' | 'max')

Arguments

ArgumentDescription
measureThe measure to work out.
dimensionThe grouping to work it out at, such as orders.customer_id. Give one or more.
summarizeHow to combine the values for each row: 'avg', 'sum', 'min' or 'max'.

Returns

The combined value on each row of the result.

Usage notes

  • The measure is worked out at those dimensions only. The query’s own grouping does not apply to it. Compare CALCULATE_PER, which adds the dimensions to the query’s grouping.
  • The call reads one source, by simple field names. Bring a joined or computed field into a source query first.
  • KATER__ALWAYS_BY writes CALCULATE_BY. A field written with one is worked out at the grouping of the query that holds it, so another query cannot read it.

Example

This Sandbox query reads the sample shop’s orders. The table shows the rows that Kater gave.

SELECT
orders.region AS "Region",
MEASURE('units_per_customer_all_regions', CALCULATE_BY(orders.sum__quantity, orders.customer_id, summarize => 'avg')) AS "Units per Customer, All Regions",
MEASURE('units_per_customer_in_region', CALCULATE_PER(orders.sum__quantity, orders.customer_id, summarize => 'avg')) AS "Units per Customer, This Region"
FROM kater_dataset.orders AS orders
WHERE
KATER__IS_NOT_NULL(orders.region)
GROUP BY
orders.region
ORDER BY
1
RegionUnits per Customer, All RegionsUnits per Customer, This Region
AMER37.629.39
APAC37.859.16
EMEA37.7010.48
LATAM37.879.91

CALCULATE_BY works out each customer’s units in every region, then averages them. CALCULATE_PER works out each customer’s units in the row’s region only.

See also