# Measures (/docs/python/datasets/measures)

Measures are aggregations over fields in a dataset. Each helper on the `measure` namespace takes the field and
optional `label`, `description`, and `filters` keyword arguments. `synonyms`, `examples`, `format`, `unit` and
`currency` describe a measure to agents, as on dimensions; derived measures accept them too.

<CodeBlock>
```python
from hypequery.datasets import measure

measures = {
    "revenue": measure.sum(
        "amount",
        label="Revenue",
        description="Total order amount before refunds.",
    ),
    "order_count": measure.count("id"),
    "unique_customers": measure.count_distinct("customer_id"),
    "average_amount": measure.avg("amount"),
    "min_amount": measure.min("amount"),
    "max_amount": measure.max("amount"),
}
```
</CodeBlock>

## Aggregations [#aggregations]

`measure.sum`, `measure.count`, `measure.count_distinct`, `measure.avg`, `measure.min`, `measure.max`,
`measure.median`, `measure.percentile(field, level)`, `measure.stddev`, `measure.variance`,
`measure.arg_max(field, by)`, and `measure.arg_min(field, by)`.

`stddev` and `variance` are **sample** statistics (`stddevSamp`, `varSamp`).
`median` and `percentile` use ClickHouse's approximate `quantile`, so expect small
differences from an exact calculation on large inputs. `count_distinct` is exact
(`uniqExact`).

Over HTTP, every non-null measure value is a string, as in TypeScript. The local
Python client returns integer counts as `int`, floating-point results as `float`,
and `Decimal` sums as `str`, so check the type before doing arithmetic.

## Filtered measures [#filtered-measures]

Pass `filters` to aggregate only matching rows:

<CodeBlock>
```python
from hypequery.datasets import filter, measure

measures = {
    "us_revenue": measure.sum("amount", filters=(filter.eq("country", "US"),)),
}
```
</CodeBlock>

Filtered measures are not supported on `arg_max` and `arg_min`.

## Derived measures [#derived-measures]

A derived measure combines other measures of the same dataset with a formula. Build the formula with the `formula`
namespace and wrap it in `measure.derived`:

<CodeBlock>
```python
from hypequery.datasets import formula, measure

measures = {
    "revenue": measure.sum("amount"),
    "order_count": measure.count("id"),
    "average_order_value": measure.derived(
        formula.divide("revenue", formula.null_if_zero("order_count")),
        label="Average order value",
    ),
}
```
</CodeBlock>

Formula helpers: `formula.add`, `formula.subtract`, `formula.multiply`, `formula.divide`, `formula.null_if_zero`,
`formula.coalesce`, `formula.round(value, decimals=0)`, `formula.floor`, and `formula.ceil`. Operands are measure
names or numeric literals. Derived measures are selected, filtered with `having`, and published like any other
measure.

## Approximate distinct counts [#approximate-distinct-counts]

`measure.approx_count_distinct("user_id")` uses ClickHouse's `uniq`, an estimate that is much cheaper than the exact
`uniqExact` on large inputs. Catalogs and contracts mark it `approximate`, and so
does any derived measure that uses it.

## Aggregate states [#aggregate-states]

For an `AggregatingMergeTree` (or a materialized view) that stores aggregate states, `measure.merge` finalizes a
state column with the matching `-Merge` combinator:

<CodeBlock>
```python
measures = {
    "users": measure.merge("uniq", "users_state"),      # uniqMerge(users_state)
    "events": measure.merge("count", "events_state"),   # countMerge, 0 when empty
    "revenue": measure.merge("sum", "revenue_state"),
}
```
</CodeBlock>

The first argument is the state's function, so hypequery knows what the column holds. Merge measures cannot take
`filters` or `sql`, and cannot be read across a relationship. To read a `ReplacingMergeTree` or
`CollapsingMergeTree` source correctly, see [row resolution](/docs/python/datasets/defining-datasets#row-resolution).

## Window measures [#window-measures]

A window measure re-aggregates a base measure from the source rows over a span of time, so a rolling distinct count is
a true distinct count, not a sum of daily counts:

<CodeBlock>
```python
measures = {
    "revenue": measure.sum("amount"),
    "active_users": measure.count_distinct("user_id"),
    "revenue_7d": measure.trailing("revenue", 7, "day"),
    "users_30d": measure.trailing("active_users", 30, "day"),
    "revenue_mtd": measure.to_date("revenue", "month"),
    "revenue_running": measure.cumulative("revenue"),
}
```
</CodeBlock>

- `trailing(measure, amount, unit)`: each bucket and the ones before it, covering `amount` `unit`s.
- `to_date(measure, grain)`: from the start of the bucket's `grain` (month-to-date, year-to-date).
- `cumulative(measure)`: all history up to the end of each bucket. It only works for aggregations that can
  accumulate: `sum`, `count`, `min` and `max`.

The dataset needs a `time_key`, and a window wraps a base measure, not a derived one.

## Period comparisons [#period-comparisons]

`measure.shift` evaluates a measure over an earlier bucket. Combine it with a derived measure for growth:

<CodeBlock>
```python
from hypequery.datasets import formula, measure

measures = {
    "revenue": measure.sum("amount"),
    "revenue_last_year": measure.shift("revenue", 1, "year"),
    "yoy_growth": measure.derived(
        formula.divide(
            formula.subtract("revenue", "revenue_last_year"),
            formula.null_if_zero("revenue_last_year"),
        )
    ),
}
```
</CodeBlock>

A shift can also wrap a window, a derived measure or another shift. The wrapped measure is recalculated over the
earlier interval rather than shifted after the fact: a prior-year year-to-date restarts on 1 January of the earlier
year, and a shifted ratio divides the earlier period's totals:

<CodeBlock>
```python
measures = {
    "revenue": measure.sum("amount"),
    "orders": measure.count("order_id"),
    "revenue_ytd": measure.to_date("revenue", "year"),
    "revenue_ytd_last_year": measure.shift("revenue_ytd", 1, "year"),
    "aov": measure.derived(formula.divide("revenue", formula.null_if_zero("orders"))),
    "aov_last_year": measure.shift("aov", 1, "year"),
    "aov_two_years_ago": measure.shift("aov_last_year", 1, "year"),
}
```
</CodeBlock>

A shift cannot read itself, directly or through a formula. Its catalog grains are the ones both the shift and the
measure it wraps support.

Calendar shifts keep the calendar date, clamping month ends: one month before 31 March is 29 February in a leap
year.

## Querying window and shift measures [#querying-window-and-shift-measures]

A query that selects a window or shift measure needs a `by` grain and exactly one bounded range on the time key,
either `between` or a `gt`/`gte` filter with an `lt`/`lte` filter:

<CodeBlock>
```python
DatasetQuery(
    by="day",
    measures=("revenue", "revenue_7d", "yoy_growth"),
    filters=(filter.gte("created_at", "2026-01-01"), filter.lt("created_at", "2026-02-01")),
)
```
</CodeBlock>

Every bucket in the range is returned, including empty ones: counts are `0`, other aggregates `None`. The grain
must divide the interval evenly: 7 days works at `day` or `week`, but not `month`. The query must also stay within
the result limit and 1,000 buckets per row, and it cannot use `having`. Results match TypeScript row for row; both
SDKs run the shared corpus in `specs/datasets/time-measures-corpus-v1.json`.

Window and shift measures are not advertised to [client endpoints](/docs/python/client-endpoints). A deployment
bundle that includes them is written as deployment contract 3, which hypequery Cloud executes.