<SYSTEM>This is the full developer documentation for MetricFlow</SYSTEM>

# MetricFlow v2

MetricFlow is a semantic layer, enabling simplified and trustworthy access to your data.

You model your data once, mapping higher-order concepts (metrics, entities, relationships, etc.) to raw data (tables, columns).
Then you integrate it everywhere (AI agents, BI tools, etc.), ensuring everyone uses the data correctly.

## Modular

MetricFlow's definitions can be split up and shared, enabling both small and massive teams to collaborate
without centralized bottlenecks.

## Expressive

MetricFlow's data model has powerful building blocks for representing complex data relationships and metric logic,
greatly reducing the data preparation and pipelines required to make your data broadly accessible.

```sql
SELECT
  customer.current_address.state,
  AVG(SUM(amount) PER (customer.id))
FROM store_sales
GROUP BY 1
```

## Vendor Neutral

MetricFlow works with any data warehouse, so you're not locked into a closed platform.

## Open Source

MetricFlow's core engine is free and permissively licensed.

## dbt Native

MetricFlow is the engine that powers the dbt Semantic Layer and has deep integrations with the larger dbt platform.

---

Want to learn more about how it works? See [Data Modeling](/metricflow/architecture).

Ready to jump in? See [Quickstart](/metricflow/quickstart).

# Quickstart

1. **[Install dbt](https://docs.getdbt.com/docs/get-started-dbt)**

2. **Install the dbt semantic layer**

    **dbt v1**

    ```sh
    pip install 'dbt-metricflow-sql[sidecar]'
    ```

    The optional `sidecar` extra is used to compile dbt models configured with `metricflow=true`.

    **dbt v2**

    MetricFlow is built into dbt v2. Turn it on with the `metricflow_v2` flag, in `dbt_project.yml`:

    ```yaml
    flags:
      metricflow_v2: true
    ```

    dbt downloads MetricFlow's sidecar the first time it needs it, to compile models configured with
    `metricflow=true`.

    **Using an AI agent?**

    The `docs` command, installed above, has all of these docs, which may be easier for your agent to
    read:

    **dbt v1**

    ```sh
    dbtsl docs
    ```

    **dbt v2**

    ```sh
    dbt sl2 docs
    ```

3. **Configure dbt Platform**

    dbt Platform makes it easy to integrate MetricFlow everywhere: agents, BI tools, etc.

    This is free and does not require running dbt jobs in Cloud, but you can skip this step and still define the
    semantic layer and compile metricflow SQL queries.

    1. [Signup](https://www.getdbt.com/signup) if you don't already have an account.

    2. Set up [dbt Platform CLI](https://docs.getdbt.com/docs/platform/dbt-cli-installation)

    3. [Configure the Semantic Layer in dbt Platform](/metricflow/dbt-platform-setup)

4. **Model your data**

    Define the semantic layer directly in your dbt project.

    See [Data Modeling](/metricflow/architecture) and [dbt](/metricflow/integrations/dbt) for details.

5. **Build you project**

    metricflow's semantic layer is compiled and built alongside your dbt project:

    ```shell
    dbt build
    ```

    `dbt parse` and `dbt compile` generate the `target/metricflow` artifact, containing everything metricflow
    needs to execute SQL queries against your warehouse.

    If dbt Platform is configured, `dbt build` will also publish the `target/metricflow` artifact to the
    metricflow server. To parse and publish to metricflow, skipping the dbt build, run:

    **dbt v1**

    ```shell
    dbtsl publish
    ```

    **dbt v2**

    ```shell
    dbt sl2 publish
    ```

6. **Query the semantic layer**

    Search over semantic layer definitions and execute queries from the command line:

    **dbt v1**

    ```shell
    dbtsl search 'revenue'
    dbtsl query 'SELECT ...'
    ```

    **dbt v2**

    ```shell
    dbt sl2 search 'revenue'
    dbt sl2 query 'SELECT ...'
    ```

    See [Data Modeling](/metricflow/architecture) for more details on how to write metricflow SQL queries.

    By default, this runs against the metricflow server running dbt Platform.

    To compile queries locally, use the `--local` flag on CLI commands:

    **dbt v1**

    ```shell
    dbtsl query --local 'SELECT ...'
    ```

    **dbt v2**

    ```shell
    dbt sl2 query --local 'SELECT ...'
    ```

# dbt Platform setup

> Set up dbt Cloud's Semantic Layer for a project with MetricFlow's `config` command, from the command line.

Before a project publishes to dbt Cloud's Semantic Layer for the first time, its account needs:

- a **profile**: a warehouse connection, which an environment runs as;
- a **login** on the profile: the warehouse credential queries run with;
- a **mapping** from a dbt Cloud group to the login, so the group's users run as it. A user in
  several mapped groups runs as the login of the mapping with the highest priority;
- or a **grant** of the login to a service token. Service tokens ignore mappings.

dbt Labs turns on MetricFlow v2 setup for the account. Then the `config` command sets up
the rest, and the first `publish` creates the environment on the profile. The account's
first environment becomes its default.

This setup doesn't change the account's existing dbt Semantic Layer, which uses MetricFlow v1. See
[Running alongside v1](/metricflow/deploying-alongside-v1).

## The recipe

Start with `status`. It is read-only, and it reports every gap, each with the command that fills
it. Its UPPERCASE arguments are placeholders to fill in.

**dbt v1**

```sh
dbtsl config status
```

**dbt v2**

```sh
dbt sl2 config status
```

1. Create the profile. Name it after the target that publishes, e.g. `prod`, or set the
   `metricflow_publish_profile` var to its name.

   **dbt v1**

   ```sh
   dbtsl config profiles create prod --adapter-type bigquery \
     --connection project_id=my-project --if-missing
   # Snowflake:
   dbtsl config profiles create prod --adapter-type snowflake --connection account=ab12345 \
     --connection database=ANALYTICS --connection warehouse=REPORTING --if-missing
   ```

   **dbt v2**

   ```sh
   dbt sl2 config profiles create prod --adapter-type bigquery \
     --connection project_id=my-project --if-missing
   # Snowflake:
   dbt sl2 config profiles create prod --adapter-type snowflake --connection account=ab12345 \
     --connection database=ANALYTICS --connection warehouse=REPORTING --if-missing
   ```

2. Create a login with its secret. Secrets come only from files and environment variables, and
   are never printed.

   **dbt v1**

   ```sh
   dbtsl config logins create --profile prod analytics_sa --keyfile ~/keys/sa.json --if-missing
   # Snowflake, with a key pair, or `--password-env VAR`:
   dbtsl config logins create --profile prod reporter --login-detail user=REPORTER \
     --login-detail role=REPORTER --private-key-file ~/keys/reporter.p8 \
     --private-key-passphrase-env SNOWFLAKE_PASSPHRASE --if-missing
   ```

   **dbt v2**

   ```sh
   dbt sl2 config logins create --profile prod analytics_sa --keyfile ~/keys/sa.json --if-missing
   # Snowflake, with a key pair, or `--password-env VAR`:
   dbt sl2 config logins create --profile prod reporter --login-detail user=REPORTER \
     --login-detail role=REPORTER --private-key-file ~/keys/reporter.p8 \
     --private-key-passphrase-env SNOWFLAKE_PASSPHRASE --if-missing
   ```

3. Map a group to the login, or grant the login to a service token, e.g. CI's. Groups and service
   tokens are named by their name or id.

   **dbt v1**

   ```sh
   dbtsl config mappings create --profile prod --login analytics_sa \
     --group Analysts --priority 100 --if-missing
   dbtsl config grants create --profile prod --login analytics_sa --service-token ci --if-missing
   ```

   **dbt v2**

   ```sh
   dbt sl2 config mappings create --profile prod --login analytics_sa \
     --group Analysts --priority 100 --if-missing
   dbt sl2 config grants create --profile prod --login analytics_sa --service-token ci --if-missing
   ```

4. Publish. This creates the environment on the profile.

   **dbt v1**

   ```sh
   dbtsl publish --target prod --vars '{metricflow_publish_profile: prod}'
   ```

   **dbt v2**

   ```sh
   dbt sl2 publish --target prod --vars '{metricflow_publish_profile: prod}'
   ```

5. Optionally, link a dbt platform environment to the Semantic Layer environment, so its jobs
   publish after each successful run:

   **dbt v1**

   ```sh
   dbtsl config environments link prod --dbt-environment 103
   ```

   **dbt v2**

   ```sh
   dbt sl2 config environments link prod --dbt-environment 103
   ```

In the dbt platform CLI, `dbt run` and `dbt build` publish to your own environment.

Then `status` reports `Ready.`

## Details

Each command's options are in its help, e.g.:

**dbt v1**

```sh
dbtsl config --help
dbtsl config logins create --help
```

**dbt v2**

```sh
dbt sl2 config --help
dbt sl2 config logins create --help
```

# Running alongside v1

> MetricFlow v2 runs next to the existing dbt Semantic Layer, which uses MetricFlow v1, without changing it.

MetricFlow v2 runs next to the existing dbt Semantic Layer, which uses MetricFlow v1. An account can use
both, and turning v2 on or off never changes v1.

## What's separate

| | v1 | v2 |
|---|---|---|
| Server | The existing Semantic Layer | A separate deployment |
| Clients connect with | GraphQL and Arrow Flight SQL | [Trino's protocol and a JSON API](/metricflow/integrations/sql) |
| Warehouse connections | The Semantic Layer's configuration | [Profiles](/metricflow/dbt-platform-setup) |

v2's profiles, logins and mappings are separate from v1's connections and credentials. Changing one
never changes the other.

## Turning v2 on

dbt Labs turns v2 on for an account with three settings, all off by default:

| Setting | Turns on |
|---|---|
| MetricFlow v2 setup | The `config` command, and queries that use the account's profiles |
| MetricFlow v2 MCP URL access | v2's MCP tools, at `?sl_version=2` |
| MetricFlow v2 MCP default | v2's MCP tools, at the MCP URL without `sl_version` |

In order:

1. Turn on **MetricFlow v2 setup**, then [set up a profile](/metricflow/dbt-platform-setup) and publish.
2. Check that queries work, over [SQL](/metricflow/integrations/sql) or the [API](/metricflow/integrations/api).
3. Turn on **MetricFlow v2 MCP URL access**, and connect an MCP client with `?sl_version=2`.
4. Optionally, turn on **MetricFlow v2 MCP default**.

The MCP settings don't check the setup setting, so turn them on only once the account is set up. Both
can also be set for one user who connects through OAuth, e.g. from Claude. Service tokens use the
account's setting.

To roll back, turn the settings off in reverse order. v1 never changes, so it needs no rollback.

## MCP

[dbt's MCP server](/metricflow/integrations/mcp) serves either v1's tools or v2's, never both. The URL
picks which:

| URL | Tools |
|---|---|
| `/api/ai/v1/mcp/?sl_version=1` | v1's |
| `/api/ai/v1/mcp/?sl_version=2` | v2's, with MCP URL access or MCP default on. Otherwise, the error "Semantic Layer v2 is unavailable for this connection." |
| `/api/ai/v1/mcp/` | v2's with MCP default on, else v1's |

To try v2 without changing an account's existing MCP clients, turn on MCP URL access, and add a second
connection with `?sl_version=2`.

v2's tools are `search_semantic_layer`, `get_semantic_layer_objects` and `execute_semantic_layer_sql`,
plus the context layer's SQL tool when it's on. The server's other tools aren't listed alongside them.
After changing the URL or a setting, reconnect the client to refresh its tools.

# Release notes

## 0.5.7

### New

- **Shorter semantics YAML.** Semantics can leave out what they used to repeat, and load the same objects:
  - An attribute, role or metric that reads one field takes that field's label and description, unless it sets its own.
  - An entity's `attributes: ['*']` reads every field of its dataset, and `'!name'` leaves one out.
  - A fact can list its roles by name, e.g. `roles: [status]`, to assign the dataset's field of that name. It declares the role, if no file does.
- **Joining datasets.** A query can `JOIN` a dataset or constellation, not just read one in `FROM`.
- **Inferred role types.** A role without a type takes the type of the facts that assign it, when they agree.
- **Readable compiled SQL.** Compiled SQL names its intermediate columns after the fields they hold, e.g. `quantity` rather than `_fill_value_0`.
- **Trino error types.** A failed query returns a Trino error name, code and type, so clients can tell SQL errors, warehouse failures and server faults apart.
- **Docs for dbt v2.** The docs show dbt v2 next to dbt v1, and Recipes are now [Common patterns](/metricflow/common-patterns).

### Fixes

- A one-to-many relationship can target a dataset whose key has a condition.
- `SELECT version()`, which Sigma's Starburst connector sends, returns the server's Trino version, instead of failing on BigQuery.
- Submitting a query returns it as queued right away, so Trino's Go client no longer reads a fast query as empty.
- `PARTITION BY EXCLUDING` a column the query doesn't group by ignores that column, instead of failing, unless the window orders by it.

### Behavior changes

- An attribute, role or metric without a label of its own now shows its field's label.

## 0.5.6

### Behavior changes

The LookML converter writes less than half as much for the same explores, and their queries compile to the same SQL.

- **Entities by join.** Every relationship with the same join shares one entity, named for the dataset and the columns it joins on, e.g. `accounts_by_salesforce_account_id` rather than `tickets__accounts_entity`. Its keys are named the same way, e.g. `accounts__salesforce_account_id`, so a query selecting a key uses the new name. Joins that differ only in what the explore joins under the view keep entities of their own, named for the joins they add, e.g. `accounts_by_salesforce_account_id_with_account_facts`.
- **Joins with `from` read their view's dataset.** `join: partner_account { from: accounts }` reads `accounts` rather than a copy of it, unless the view's fields convert differently for the join.
- **A field's `meta` keeps only `hidden`.** A converted field has `meta.hidden: true` when Looker hides it, and no longer names its view, field, kind, group label, view label or tags. Datasets and constellations keep `meta.lookml` with their view or explore.

## 0.5.5

### New

- **Which objects the caller can use.** Given the caller's groups, every GraphQL node has `accessible`: whether its own permissions, and those of the object it's on, let the caller use it. It doesn't check what an object reads, so a constellation over a dataset the caller can't use shows as accessible, and its queries fail.
- **Inferred types in GraphQL.** `resolvedRoles` and `resolvedMetrics` return each field's declared or inferred type, including a metric's type where another constellation imports it. To fill them in on an existing registry, run `python -m metricflow_db rebuild-resolved`, then reapply `grant_metadata_role` for restricted metadata readers.
- **Relationships that always match.** A many-to-one relationship to a dataset can declare `always_matches: true` when every non-NULL key has a row in the target, like a foreign key. The target's key fields are then read without a join.
- **Filtering the dimension a window orders by.** When a window leaves a `GROUP BY` key out of its partition and orders by it, as in `PARTITION BY EXCLUDING d ORDER BY d`, a `WHERE` on that key filters after the window. A previous-day metric filtered to a date range then still reads the day before the range. A permission's condition still filters first.
- **LookML views that read the base view.** A view joined on the base view's primary key can read the base's dimensions, e.g. `${opportunities.stage_0_date}` in a view joined to `opportunities`.

### Fixes

- A value read through a join that repeats rows is picked with `ANY_VALUE` rather than `MAX`, so BigQuery accepts values `MAX` can't take, such as a STRUCT. A value under a `FILTER` still uses `MAX`.
- A `GROUP BY` key that holds a subquery is computed below the aggregation, so BigQuery accepts it.
- A query whose `PER` sits beside the compiler's own fan-out protection compiles, instead of failing with "a PER cannot add a column another grouping set already groups by".
- Two GraphQL requests that ask for the same field's type at once both get it, instead of one getting `null`.
- An invalid relationship path fails with a clearer error.

### Behavior changes

- Reading the key field of a many-to-one relationship to a dataset, e.g. `refund.order_id`, goes through the join, so it's NULL when no row matches. Declare `always_matches: true` to read it without the join.

## 0.5.4

### New

- **Windows over aggregates.** A window over an aggregate, e.g. `LAG(SUM(x)) OVER (ORDER BY month)`, runs over the aggregation in a subquery, so BigQuery accepts a window that orders or partitions by a grouped expression.
- **Looker time zones on BigQuery.** Trino's `FORMAT_DATETIME`, which Looker writes when it converts a time to the query's time zone, compiles to BigQuery.

### Fixes

- An aggregate over a join the query writes itself counts each row once, as relationship joins already do. A join that may repeat rows aggregates by the key of the source it reads; when it can't count each row once, it fails with "Aggregate crosses a fan-out join" instead of returning a wrong total.
- `UNNEST` of an array column through a many-to-one relationship, e.g. `UNNEST(advertiser.periods)`, compiles again, in `EXISTS`, in `JOIN UNNEST` onto a dataset with a key, and in a calculation's subquery.
- `UNNEST` of a many-to-one relationship, or of a path past a one-to-many relationship, fails with a clear error instead of ignoring the rest of the path.

### Behavior changes

- `COUNT(*)` over a join the query writes that may repeat rows counts the root's rows, not the joined ones. A plain `SUM` of a joined subquery's column is an error.

## 0.5.3

### New

- **Inferred types in the information schema.** `information_schema.columns` reports the type of a calculation or metric that doesn't declare one, instead of `varchar`.
- **LookML parameter values.** The LookML converter now converts Liquid that switches on a parameter's value, e.g. `{% if orders.refunds._parameter_value == 'include' %}`, and passes it to the dataset as a boolean parameter.
- **Looker time zones.** When Looker's connection to the semantic layer has a query time zone, the LookML converter's `--looker-converts` leaves the time fields Looker converts in UTC, so they aren't converted twice.

### Fixes

- Compiling without a default warehouse catalog works again, e.g. for a Databricks profile without one. A dataset's table must then name its catalog and schema.
- A raw warehouse table can be queried unless a dataset with permissions reads it.
- A constellation query that reads only metrics, without aggregating them, compiles. It used to compile to an empty `SELECT`.
- A measure behind a one-to-many relationship and then a many-to-one relationship counts each of its own rows once, instead of once per row of the dataset in between.
- Trino SQL with `LIKE ... ESCAPE`, or with `AT TIME ZONE` on a time without a zone, compiles to BigQuery.
- Legacy semantics convert to a bundle the server loads when an entity has its semantic model's name, or a source column's name in another case. A dimension that's a constant, such as `1`, compiles.

## 0.5.2

### New

- **Access control.** Datasets, entities, constellations and their fields take `permissions` by dbt platform group: rows a group can read, aggregates it can see, and columns it gets masked. See [Access](/metricflow/access).
- **Time spines.** `ORDER BY ... WITH FILL` and `PER (... WITH FILL)` fill the gaps in a time series, from a subquery or a relationship to a dataset of dates. See [SQL extensions](/metricflow/reference/sql/extensions).
- **Filtering through one-to-many relationships.** A query can read a one-to-many relationship's rows with `EXISTS (SELECT ... FROM UNNEST(...))`.
- **Coarser grains in windows.** Cumulative, grain-to-date and offset windows work when a query groups by a coarser grain than the window's time column, e.g. `DATE_TRUNC('month', metric_time)`.
- **GraphQL metadata API.** Read a bundle's objects over GraphQL. See [API](/metricflow/integrations/api).
- **Search by type.** Search results carry each object's type, label, description and parent, can be filtered by type, and come in pages.
- **More LookML joins and custom measures.** The LookML converter now converts joins that match on columns from two other views, and keeps simple measures' types, so Looker can build custom measures on them.

### Fixes

- A `sql` dataset inside a subquery keeps its own unqualified columns, instead of reading them as the outer dataset's.
- The dbt plugin keeps column `permissions` and `policy`, accepts `semantics.policies`, and reads an unquoted `on:` in a dataset key.
- A LookML join from another view reads its own copy of that view.
- Upgrading `dbt-metricflow-sql[sidecar]` upgrades the sidecar too, and the sidecar reads Pages with YAML frontmatter.

## 0.5.1

### New

- **Publishing from dbt platform jobs.** Link a dbt platform environment to a Semantic Layer environment with `dbtsl config environments link`, and its jobs publish the bundle after each successful `dbt run` or `dbt build`. See [dbt platform setup](/metricflow/dbt-platform-setup).
- **One-to-many joins in LookML.** The LookML converter now converts an explore's `one_to_many` joins, and the views joined through them, counting each joined row once. A one-to-many join to a view without a primary key is still left out.
- **More LookML measures.** The LookML converter now converts `min` measures, and `sum_distinct`, `average_distinct` and `median_distinct` measures whose `sql_distinct_key` isn't the view's primary key.

### Fixes

- Loading a fragment keeps each object's `meta`, and each entity's and fact's label and description.

## 0.5.0

### Upgrading

- A constellation's datasets, and the roles they provide, are now listed under `facts` instead of `assignments`. Rename the key in your semantics: fragments that still use `assignments` fail to load. See [Constellations](/metricflow/constellations).
- Publish your bundles again once you upgrade. A server on 0.5.0 can't read bundles published before it.

### New

- **Macros.** Semantics, dataset fields and pages in a dbt schema file can call the project's macros, e.g. `{{ order_size('gross') }}`. See [Macros](/metricflow/integrations/dbt#macros).
- **Aliases.** A constellation can use the same dataset more than once, each time under its own `alias` with its own roles. See [Constellations](/metricflow/constellations).
- **LookML labels.** The LookML converter keeps each field's label and description, and records the Looker view and field it came from under `meta.lookml`.

### Fixes

- The LookML converter now converts explores with a join on several views, leaving that join out, and reads a join with `from:` as a copy of that view.
- `dbtsl config` works for dbt Cloud CLI users, who have no `profiles.yml`.

# Architecture

MetricFlow is the engine that powers the dbt semantic layer.

MetricFlow is configured using three table-like concepts: **datasets**, **entities**, and **constellations**.

Clients query MetricFlow with simple input SQL, referencing these table-like concepts,
and MetricFlow compiles that to complex output SQL against your data warehouse.

Together, these form the building blocks for a composable, modular, and expressive semantic layer.

## Core Concepts

### Dataset

Table, layered with virtual columns.

In dbt, datasets are 1-to-1 with models or sources.

Datasets let you centralize complex business logic (aggregations, joins, etc) and query it like any other column.

- **Column** Column of the table.
- **Relationship** Named reference to another table.
- **Calculation** Expression referencing columns, relationships, or other calculations.

[Datasets →](/metricflow/datasets)

### Entity

Virtual wide table, composed from many datasets.

Entities allow a single business concept to be composed from many tables, owned and maintained by many teams.

- **Source** Dataset the entity is composed of and how to join it.
- **Attribute** Expression referencing one or many source columns.

[Entities →](/metricflow/entities)

### Constellation

Virtual union of datasets, merged on a set of common roles, and queried as a single table.

Constellations allow metrics to span many tables and let you query them as a single table.

- **Metric** Aggregate expression spanning one or many datasets.
- **Role** What metrics can be grouped and filtered by.
- **Fact** A dataset of the constellation, and how it implements each role.

[Constellations →](/metricflow/constellations)

# Datasets

Datasets are tables, layered with virtual columns.

Datasets let you centralize complex business logic (aggregations, joins, etc) and query it like any other column.

Here's how the above might be configured in YAML:

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: customer_id
        - name: gross
        - name: discount
        - name: order_id
        - name: sold_at
    calculations:
      - name: net
        expr: gross - discount
      - name: revenue
        expr: SUM(net)
    relationships:
      - name: customer
        target: profiles
        key: [{ name: id, expr: customer_id }]
    key: [order_id]
  - name: profiles
    source:
      location: shop.profiles
      columns:
        - name: id
        - name: plan
    key: [id]
```

And queried with MetricFlow SQL extensions:

Input SQL:

```sql
SELECT
  customer.plan,
  AGG(revenue)
FROM orders
WHERE net > 0
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "customer"."plan" AS "plan",
  SUM((
    "orders"."gross" - "orders"."discount"
  )) AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."profiles" AS "customer"
  ON "customer"."id" = "orders"."customer_id"
WHERE
  (
    "orders"."gross" - "orders"."discount"
  ) > 0
GROUP BY
  "customer"."plan"
```

## Calculations

Calculations are arbitrary SQL expressions. They can include columns, other calculations, or relationships.

Calculations can be aggregate expressions, in which case they must be queried using the `AGG` function.

## Relationships

Relationships are named references to a another dataset or entity.
Relationships can be traversed using the dot notation, and the compiler automatically adds necessary joins.

## Key conditions

Let's look at a more complex relationship example:

```yaml
datasets:
  # Adding a relationship to the previous `orders` dataset
  - name: orders
    relationships:
      - name: plan
        target: plan_history
        key:
          - { name: customer_id, expr: customer_id }
          - { name: as_of, expr: sold_at }
  # SCD Type 2 dataset
  - name: plan_history
    source:
      location: shop.plan_history
      columns:
        - name: customer_id
        - name: name
        - name: valid_from
        - name: valid_to
    key:
      - customer_id
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
```

Input SQL:

```sql
SELECT
  order_id,
  plan.name
FROM orders
```

Compiled SQL:

```sql
SELECT
  "orders"."order_id" AS "order_id",
  "plan"."name" AS "name"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."plan_history" AS "plan"
  ON "plan"."customer_id" = "orders"."customer_id"
  AND (
    "orders"."sold_at" >= "plan"."valid_from"
    AND (
      "plan"."valid_to" IS NULL OR "orders"."sold_at" < "plan"."valid_to"
    )
  )
```

Datasets can define a unique `key`.
Keys can be defined as logical conditions, supporting concepts like "slowly changing dimensions (SCD Type 2)".

## Multi-hop joins

```yaml
datasets:
  # Adding a relationship to the previous `plan_history` dataset
  - name: plan_history
    relationships:
      - name: details
        target: plans
        key:
          - { name: name, expr: name }
          - { name: as_of, expr: ":as_of" }
  # Leaf in this chain of relationships
  - name: plans
    source:
      location: shop.plans
      columns:
        - name: name
        - name: price
        - name: valid_from
        - name: valid_to
    key:
      - name
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
```

Input SQL:

```sql
SELECT
  order_id,
  plan.details.price
FROM orders
```

Compiled SQL:

```sql
SELECT
  "orders"."order_id" AS "order_id",
  "plan_details"."price" AS "price"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."plan_history" AS "plan"
  ON "plan"."customer_id" = "orders"."customer_id"
  AND (
    "orders"."sold_at" >= "plan"."valid_from"
    AND (
      "plan"."valid_to" IS NULL OR "orders"."sold_at" < "plan"."valid_to"
    )
  )
LEFT JOIN "shop"."plans" AS "plan_details"
  ON "plan_details"."name" = "plan"."name"
  AND (
    "orders"."sold_at" >= "plan_details"."valid_from"
    AND (
      "plan_details"."valid_to" IS NULL
      OR "orders"."sold_at" < "plan_details"."valid_to"
    )
  )
```

Using the same dot notation, relationships can be traversed to arbitrary depth.

Relationship join keys can be propagated across hops, which is useful for chaining SCD Type 2 datasets.

## One-to-many relationships

```yaml
datasets:
  - name: profiles
    relationships:
      - name: orders
        target: orders
        key: [{ name: customer_id, expr: id }]
```

Input SQL:

```sql
SELECT
  plan,
  AGG(orders.revenue)
FROM profiles
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."plan" AS "plan",
  SUM("grouped"."revenue") AS "revenue"
FROM (
  SELECT
    "profiles"."plan" AS "plan",
    ANY_VALUE(
      CASE
        WHEN NOT "orders"."order_id" IS NULL
        THEN (
          "orders"."gross" - "orders"."discount"
        )
      END
    ) AS "revenue"
  FROM "shop"."profiles" AS "profiles"
  LEFT JOIN "shop"."orders" AS "orders"
    ON "orders"."customer_id" = "profiles"."id"
  GROUP BY
    "profiles"."plan",
    "orders"."order_id"
) AS "grouped"
GROUP BY
  "grouped"."plan"
```

When a relationship doesn't reference another dataset's `key`, it is a one-to-many relationship.
A query can `AGG` calculations from a one-to-many relationship, and the compiler applies fan-out protection to avoid double-counting.

## Higher-order calculations

Calculations can use window functions and `PER`, for metrics like running totals, shares of the total, and averages per customer.
See [Complex metrics](/metricflow/complex-metrics).

# Entities

Entities are virtual wide datasets.

They allow a single business concept to be composed from many tables, owned and maintained by many teams.

```yaml
entities:
  - name: customer
    key:
      - name: id
        datatype: INT
    sources:
      - dataset: profiles
        on: id = :id
      - dataset: acquisition
        on: customer_id = :id
      - dataset: delivery
        on: customer_id = :id
    attributes:
      - name: plan
        expr: profiles.plan
      - name: channel
        expr: acquisition.channel
      - name: zone
        expr: delivery.zone
datasets:
  - name: orders
    relationships:
      - name: customer
        target: customer
        key: [{ name: id, expr: customer_id }]
```

Input SQL:

```sql
SELECT
  customer.plan,
  customer.channel,
  customer.zone,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "customer"."plan" AS "plan",
  "customer_2"."channel" AS "channel",
  "customer_3"."zone" AS "zone",
  SUM((
    "orders"."gross" - "orders"."discount"
  )) AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."profiles" AS "customer"
  ON "customer"."id" = "orders"."customer_id"
LEFT JOIN "marketing"."acquisition" AS "customer_2"
  ON "customer_2"."customer_id" = "orders"."customer_id"
LEFT JOIN "operations"."delivery" AS "customer_3"
  ON "customer_3"."customer_id" = "orders"."customer_id"
GROUP BY
  "customer"."plan",
  "customer_2"."channel",
  "customer_3"."zone"
```

## Sources

Sources are the datasets an entity is composed of. Each says how it joins to the entity's key with
`on`, where `:placeholders` are the key's values.

Unlike a SQL view, a query only joins the sources it uses, and an entity can be [defined across many files](/metricflow/composability#modularity).

## Attributes

Attributes are an entity's columns. Each is an expression over zero to many sources.

An entity with one source can list its source's fields by name instead, each read as
`<dataset>.<field>`. `'*'` lists every column and calculation, and `'!name'` leaves one out:

```yaml
attributes: ['*', '!ssn']
```

An attribute that reads one field, e.g. `profiles.plan`, inherits the field's `label`,
`description` and `meta`.

Relationships can target an entity instead of a dataset, giving the dataset access to all an entity's sources and attributes.

# Constellations

Constellations are a virtual union of datasets, merged on a set of common "roles".

They allow metrics to span many tables and let you query them as a single table.

```yaml
constellations:
  - name: finance
    metrics:
      - name: revenue
        expr: AGG(orders.revenue)
      - name: cost
        expr: AGG(shipments.cost)
      - name: margin
        expr: AGG(revenue) - AGG(cost)
    roles:
      - name: date
      - name: customer
        datatype: REF(customer)
    facts:
      - dataset: orders
        roles:
          - name: date
            expr: sold_at
          - name: customer
            expr: customer
      - dataset: shipments
        roles:
          - name: date
            expr: shipped_at
          - name: customer
            expr: shipped_to
datasets:
  # Adding another dataset that our `finance` constellation spans
  - name: shipments
    source:
      location: operations.shipments
      columns:
        - name: shipped_at
        - name: shipping
        - name: customer_id
        - name: shipment_id
    key: [shipment_id]
    calculations:
      - name: cost
        expr: SUM(shipping)
    relationships:
      - name: shipped_to
        target: customer
        key: [{ name: id, expr: customer_id }]
```

Input SQL:

```sql
SELECT
  date,
  customer.channel,
  AGG(margin)
FROM finance
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "finance"."date" AS "date",
  "finance"."customer_channel" AS "channel",
  COALESCE("finance"."revenue", 0) - COALESCE("finance"."cost", 0) AS "margin"
FROM (
  SELECT
    COALESCE("orders"."date", "shipments"."date") AS "date",
    COALESCE("orders"."customer_channel", "shipments"."customer_channel") AS "customer_channel",
    MAX("orders"."revenue") AS "revenue",
    MAX("shipments"."cost") AS "cost"
  FROM (
    SELECT
      "orders"."sold_at" AS "date",
      "customer"."channel" AS "customer_channel",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "marketing"."acquisition" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      "orders"."sold_at",
      "customer"."channel"
  ) AS "orders"
  FULL OUTER JOIN (
    SELECT
      "shipments"."shipped_at" AS "date",
      "shipped_to"."channel" AS "customer_channel",
      SUM("shipments"."shipping") AS "cost"
    FROM "operations"."shipments" AS "shipments"
    LEFT JOIN "marketing"."acquisition" AS "shipped_to"
      ON "shipped_to"."customer_id" = "shipments"."customer_id"
    GROUP BY
      "shipments"."shipped_at",
      "shipped_to"."channel"
  ) AS "shipments"
    ON "shipments"."date" = "orders"."date"
    AND "shipments"."customer_channel" = "orders"."customer_channel"
  GROUP BY
    COALESCE("orders"."date", "shipments"."date"),
    COALESCE("orders"."customer_channel", "shipments"."customer_channel")
) AS "finance"
```

## Metrics

Metrics are aggregate SQL expressions that span one to many datasets.

Metrics can reference other metrics.

A metric that only aggregates one field with `AGG`, e.g. `AGG(orders.revenue)`, inherits the
field's `label`, `description` and `meta`.

## Roles

Roles are what you can group and filter metrics by.
Roles are abstract - they can be a primitive datatype (e.g. `TIMESTAMP`) or a relationship (e.g. `REF(user)`).

When aggregating metrics, aggregation is first done per dataset, then joined on any roles being grouped by.

## Facts

Facts are the datasets the metrics read. Each fact assigns arbitrary SQL expressions to roles, which define how its dataset implements each role.

Each fact can take an `alias`, which defaults to the dataset's name. Metrics read facts by alias, so a constellation can use the same dataset more than once.

A fact can list a role by name alone to assign it the dataset's field of that name. A role
listed this way is added to the constellation if it's missing:

```yaml
facts:
  - dataset: orders
    roles: [status, { name: date, expr: ordered_at }]
```

A role inherits the `label`, `description` and `meta` of the first field of the same name that a
fact assigns it.

## Imports

A constellation can import another's fields:

```yaml
constellations:
  - name: sales
    imports:
      - constellation: finance
        fields:
          # import all fields
          - '*'
          # except these:
          - '!cost'
          - '!margin'
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('quarter', date) AS quarter,
  AGG(revenue)
FROM sales
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "sales"."quarter" AS "quarter",
  "sales"."revenue" AS "revenue"
FROM (
  SELECT
    "orders"."quarter",
    "orders"."revenue"
  FROM (
    SELECT
      DATE_TRUNC('QUARTER', "orders"."sold_at") AS "quarter",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue"
    FROM "shop"."orders" AS "orders"
    GROUP BY
      DATE_TRUNC('QUARTER', "orders"."sold_at")
  ) AS "orders"
) AS "sales"
```

# Composability

Datasets, entities, and constellations are building blocks that all work together.

You can combine them to achieve many classical analytical modeling problems -
fact constellations, snowflake schemas, dimension conforming, data vault hub and spokes, etc. -
all queryable as simple SQL.

## Modularity

Every object can be split across many files, owned by many teams.

Files that define the same object are merged.

`orders.yaml`:

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: customer_id
        - name: gross
        - name: sold_at
```

`orders_extra.yaml`:

```yaml
datasets:
  - name: orders
    calculations:
      - name: revenue
        expr: SUM(gross)
    relationships:
      - name: customer
        target: customer
        key: [{ name: id, expr: customer_id }]
```

`customer.yaml`:

```yaml
entities:
  - name: customer
    key:
      - name: id
```

`customer_extra.yaml`:

```yaml
datasets:
  - name: acquisition
    source:
      location: marketing.acquisition
      columns:
        - name: customer_id
        - name: channel
entities:
  - name: customer
    sources:
      - dataset: acquisition
        on: customer_id = :id
    attributes:
      - name: channel
        expr: acquisition.channel
```

`finance.yaml`:

```yaml
constellations:
  - name: finance
    roles:
      - name: date
      - name: customer
        datatype: REF(customer)
```

`finance_extra.yaml`:

```yaml
constellations:
  - name: finance
    metrics:
      - name: revenue
        expr: AGG(orders.revenue)
    facts:
      - dataset: orders
        roles:
          - name: date
            expr: sold_at
          - name: customer
            expr: customer
```

# Pages

Pages are markdown documents defined alongside the semantic layer.

They hold any context needed to use the semantic layer effectively that doesn't fit into a single metric, role, etc.

## Writing pages

`wiki/glossary.md`:

```md
---
label: Glossary
description: What our metrics mean.
---

[Margin](metric:finance:margin) is what orders earn after costs.
Every order is in the [orders](dataset:orders) dataset.

New here? Start with [onboarding](guides/onboarding.md).
```

The frontmatter sets the page's `label` and `description`, and any `meta`.

Pages link to other objects with ordinary markdown links, using the object's reference as the URL:

| Reference | Links to |
|---|---|
| `dataset:orders`, `entity:customer`, `constellation:finance` | A dataset, entity, or constellation |
| `metric:finance:margin`, `role:finance:customer` | A constellation's metric or role |
| `column:orders:gross`, `calculation:orders:revenue`, `relationship:orders:customer` | A dataset's field |
| `attribute:customer:plan` | An entity's attribute |
| `page:guides/onboarding` | Another page |

To link to another page, use a relative path to its file.

## Registering pages

The top-level `pages` key points at markdown files:

```yaml
pages:
  - path: wiki
```

Every `.md` file under `wiki` becomes a page, named by its path without `.md`: `wiki/glossary.md` is `glossary`, and `wiki/guides/onboarding.md` is `guides/onboarding`.

`path` is relative to the file that declares it. It can be a directory, a single file, or a glob.

## Reading pages

Pages are chunked, indexed, and made searchable through the API and MCP.

# Complex metrics

Many metrics aren't a single aggregate over rows: a running total, a share of the total, a change from the previous period, or an average of each customer's total.
In plain SQL, each takes a window function or a nested subquery, rewritten for every grain a report needs.

MetricFlow SQL has three building blocks for them: window functions over aggregates, `PER`, and `WITH FILL`.
Each can be defined once, as calculations or metrics, and adapt to whatever a query groups by.

## Window functions: `OVER`

A window function over `AGG` runs over the query's rows, after they're grouped.

```yaml
datasets:
  - name: orders
    calculations:
      - name: revenue_past_7d
        expr: >-
          SUM(AGG(revenue)) OVER (
            PARTITION BY EXCLUDING sold_at
            ORDER BY sold_at
            RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW
          )
      - name: revenue_share_of_total
        expr: AGG(revenue) / SUM(AGG(revenue)) OVER ()
```

Input SQL:

```sql
SELECT
  sold_at,
  customer.channel,
  AGG(revenue_past_7d),
  AGG(revenue_share_of_total)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "aggregated"."sold_at" AS "sold_at",
  "aggregated"."channel" AS "channel",
  SUM("aggregated"."revenue") OVER (
    PARTITION BY "aggregated"."channel"
    ORDER BY "aggregated"."sold_at"
    RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
  ) AS "revenue_past_7d",
  "aggregated"."revenue" / SUM("aggregated"."revenue") OVER () AS "revenue_share_of_total"
FROM (
  SELECT
    "orders"."sold_at" AS "sold_at",
    "customer"."channel" AS "channel",
    SUM((
      "orders"."gross" - "orders"."discount"
    )) AS "revenue"
  FROM "shop"."orders" AS "orders"
  LEFT JOIN "marketing"."acquisition" AS "customer"
    ON "customer"."customer_id" = "orders"."customer_id"
  GROUP BY
    "orders"."sold_at",
    "customer"."channel"
) AS "aggregated"
```

`PARTITION BY EXCLUDING` partitions by everything the query groups by, except the columns it lists.
This query groups by `sold_at` and `channel`, so the running total is partitioned by `channel`.
Grouped by `sold_at` alone, the same calculation would span every channel.

A window with no `PARTITION BY` spans every row, so this is each row's share of the query's total.

See [Window functions](/metricflow/reference/sql/extensions#window-functions) for the syntax.

## Multi-level aggregation: `PER`

`f(aggregate PER (columns))` aggregates in two steps: first `aggregate`, at the query's grain plus `columns`, then `f` over those values, back to the query's grain.

```yaml
datasets:
  - name: orders
    calculations:
      - name: avg_revenue_per_customer
        expr: AVG(AGG(revenue) PER (customer.id))
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', sold_at) AS month,
  AGG(avg_revenue_per_customer),
  MAX(AGG(revenue) PER (customer.id)) AS top_customer_revenue
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."month" AS "month",
  AVG("grouped"."avg_revenue_per_customer") AS "avg_revenue_per_customer",
  MAX("grouped"."avg_revenue_per_customer") AS "top_customer_revenue"
FROM (
  SELECT
    DATE_TRUNC('MONTH', "orders"."sold_at") AS "month",
    SUM((
      "orders"."gross" - "orders"."discount"
    )) AS "avg_revenue_per_customer"
  FROM "shop"."orders" AS "orders"
  GROUP BY
    DATE_TRUNC('MONTH', "orders"."sold_at"),
    "orders"."customer_id"
) AS "grouped"
GROUP BY
  "grouped"."month"
```

Revenue is summed per customer, then averaged: each month's average revenue per customer, rather than per order.

`PER` can also be written in a query, and any aggregate can combine the values, e.g. `MAX`, for the top customer's revenue.

See [Multi-level aggregation](/metricflow/reference/sql/extensions#multi-level-aggregation) for the syntax.

## Spines: `WITH FILL`

A spine is a dataset with a complete set of values for a particular domain, e.g. a date spine might have one row for each calendar day.
Spines can be used to fill gaps when an aggregate calculation depends on a row being present for all values, e.g. an average over the past 7 days.

```yaml
datasets:
  - name: calendar
    source:
      location: shop.calendar
      columns:
        - name: day
    key: [day]
  - name: orders
    relationships:
      - name: sold_on
        target: calendar
        key: [{ name: day, expr: CAST(sold_at AS DATE) }]
        always_matches: true
    calculations:
      - name: avg_daily_revenue
        expr: AVG(COALESCE(AGG(revenue), 0) PER (sold_on.day WITH FILL))
```

Input SQL:

```sql
SELECT
  customer.channel,
  AGG(avg_daily_revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."channel" AS "channel",
  AVG("grouped"."avg_daily_revenue") AS "avg_daily_revenue"
FROM (
  WITH "_unfilled" AS (
    SELECT
      "customer"."channel" AS "channel",
      CAST("orders"."sold_at" AS DATE) AS "_fill_dimension_1",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue",
      COUNT(*) AS "_rows"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "marketing"."acquisition" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      "customer"."channel",
      CAST("orders"."sold_at" AS DATE)
  )
  SELECT
    "filled"."channel" AS "channel",
    COALESCE("filled"."revenue", 0) AS "avg_daily_revenue",
    "filled"."_rows" AS "_rows"
  FROM (
    SELECT
      COALESCE("_unfilled"."channel", "keys"."channel") AS "channel",
      COALESCE("_unfilled"."_fill_dimension_1", "keys"."_fill_dimension_1") AS "_fill_dimension_1",
      "_unfilled"."revenue" AS "revenue",
      "_unfilled"."_rows" AS "_rows"
    FROM (
      SELECT
        "parts"."channel",
        "spine"."_fill_col" AS "_fill_dimension_1"
      FROM (
        SELECT DISTINCT
          "sold_on"."day" AS "_fill_col"
        FROM "shop"."calendar" AS "sold_on"
      ) AS "spine"
      CROSS JOIN (
        SELECT DISTINCT
          "channel"
        FROM "_unfilled"
        WHERE
          NOT "_fill_dimension_1" IS NULL
      ) AS "parts"
      WHERE
        "spine"."_fill_col" BETWEEN (
          SELECT
            MIN("_fill_dimension_1")
          FROM "_unfilled"
        ) AND (
          SELECT
            MAX("_fill_dimension_1")
          FROM "_unfilled"
        )
    ) AS "keys"
    FULL OUTER JOIN "_unfilled"
      ON "_unfilled"."_fill_dimension_1" = "keys"."_fill_dimension_1"
      AND "_unfilled"."channel" IS NOT DISTINCT FROM "keys"."channel"
  ) AS "filled"
) AS "grouped"
GROUP BY
  "grouped"."channel"
HAVING
  NOT MAX("grouped"."_rows") IS NULL
```

`PER (sold_on.day WITH FILL)` uses the `calendar` dataset and `COALESCE` to fill missing days with `0`, ensuring the average counts every day, not just days with orders.

Input SQL:

```sql
SELECT
  sold_on.day,
  AGG(revenue)
FROM orders
GROUP BY ALL
ORDER BY sold_on.day WITH FILL
```

Compiled SQL:

```sql
SELECT
  "orders"."day" AS "day",
  "orders"."revenue" AS "revenue"
FROM (
  WITH "_unfilled" AS (
    SELECT
      CAST("orders"."sold_at" AS DATE) AS "day",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue"
    FROM "shop"."orders" AS "orders"
    GROUP BY
      CAST("orders"."sold_at" AS DATE)
  )
  SELECT
    "filled"."day" AS "day",
    "filled"."revenue" AS "revenue"
  FROM (
    SELECT
      COALESCE("_unfilled"."day", "keys"."day") AS "day",
      "_unfilled"."revenue" AS "revenue"
    FROM (
      SELECT
        "spine"."_fill_col" AS "day"
      FROM (
        SELECT DISTINCT
          "sold_on"."day" AS "_fill_col"
        FROM "shop"."calendar" AS "sold_on"
      ) AS "spine"
      WHERE
        "spine"."_fill_col" BETWEEN (
          SELECT
            MIN("day")
          FROM "_unfilled"
        ) AND (
          SELECT
            MAX("day")
          FROM "_unfilled"
        )
    ) AS "keys"
    FULL OUTER JOIN "_unfilled"
      ON "_unfilled"."day" = "keys"."day"
  ) AS "filled"
) AS "orders"
ORDER BY
  "day"
```

`ORDER BY ... WITH FILL` can similarly be used to ensure a result set includes all days, with NULL revenue for days without orders.

See [Filling missing values](/metricflow/reference/sql/extensions#filling-missing-values) for the syntax.

## `OVER`, `PER`, and `WITH FILL` together

Windows and `PER` nest, in either order, and a `PER` can be filled.

```yaml
datasets:
  - name: orders
    calculations:
      - name: avg_revenue_per_customer_change
        expr: >-
          AGG(avg_revenue_per_customer) - LAG(AGG(avg_revenue_per_customer)) OVER (
            PARTITION BY EXCLUDING sold_at
            ORDER BY sold_at
          )
```

Input SQL:

```sql
SELECT
  sold_at,
  customer.channel,
  AGG(avg_revenue_per_customer),
  AGG(avg_revenue_per_customer_change)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "aggregated"."sold_at" AS "sold_at",
  "aggregated"."channel" AS "channel",
  "aggregated"."avg_revenue_per_customer" AS "avg_revenue_per_customer",
  "aggregated"."avg_revenue_per_customer" - LAG("aggregated"."avg_revenue_per_customer") OVER (PARTITION BY "aggregated"."channel" ORDER BY "aggregated"."sold_at") AS "avg_revenue_per_customer_change"
FROM (
  SELECT
    "grouped"."sold_at" AS "sold_at",
    "grouped"."channel" AS "channel",
    AVG("grouped"."avg_revenue_per_customer") AS "avg_revenue_per_customer"
  FROM (
    SELECT
      "orders"."sold_at" AS "sold_at",
      "customer"."channel" AS "channel",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "avg_revenue_per_customer"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "marketing"."acquisition" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      "orders"."sold_at",
      "customer"."channel",
      "orders"."customer_id"
  ) AS "grouped"
  GROUP BY
    "grouped"."sold_at",
    "grouped"."channel"
) AS "aggregated"
```

A window over a `PER`: the day-over-day change in average revenue per customer, by channel.
A window can also go inside a `PER`, where it runs at the `PER`'s grain, e.g. to average each customer's own change.

A window inside a filled `PER` reads every period, including those without rows:

```yaml
datasets:
  - name: orders
    calculations:
      - name: biggest_daily_drop
        expr: >-
          MAX(
            LAG(COALESCE(AGG(revenue), 0)) OVER (
              PARTITION BY EXCLUDING sold_on.day
              ORDER BY sold_on.day
            ) - COALESCE(AGG(revenue), 0)
            PER (sold_on.day WITH FILL)
          )
```

Input SQL:

```sql
SELECT
  customer.channel,
  AGG(biggest_daily_drop)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."channel" AS "channel",
  MAX("grouped"."biggest_daily_drop") AS "biggest_daily_drop"
FROM (
  WITH "_unfilled" AS (
    SELECT
      "customer"."channel" AS "channel",
      CAST("orders"."sold_at" AS DATE) AS "_fill_dimension_1",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue",
      COUNT(*) AS "_rows"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "marketing"."acquisition" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      "customer"."channel",
      CAST("orders"."sold_at" AS DATE)
  )
  SELECT
    "filled"."channel" AS "channel",
    LAG(COALESCE("filled"."revenue", 0)) OVER (PARTITION BY "filled"."channel" ORDER BY "filled"."_fill_dimension_1") - COALESCE("filled"."revenue", 0) AS "biggest_daily_drop",
    "filled"."_rows" AS "_rows"
  FROM (
    SELECT
      COALESCE("_unfilled"."channel", "keys"."channel") AS "channel",
      COALESCE("_unfilled"."_fill_dimension_1", "keys"."_fill_dimension_1") AS "_fill_dimension_1",
      "_unfilled"."revenue" AS "revenue",
      "_unfilled"."_rows" AS "_rows"
    FROM (
      SELECT
        "parts"."channel",
        "spine"."_fill_col" AS "_fill_dimension_1"
      FROM (
        SELECT DISTINCT
          "sold_on"."day" AS "_fill_col"
        FROM "shop"."calendar" AS "sold_on"
      ) AS "spine"
      CROSS JOIN (
        SELECT DISTINCT
          "channel"
        FROM "_unfilled"
        WHERE
          NOT "_fill_dimension_1" IS NULL
      ) AS "parts"
      WHERE
        "spine"."_fill_col" BETWEEN (
          SELECT
            MIN("_fill_dimension_1")
          FROM "_unfilled"
        ) AND (
          SELECT
            MAX("_fill_dimension_1")
          FROM "_unfilled"
        )
    ) AS "keys"
    FULL OUTER JOIN "_unfilled"
      ON "_unfilled"."_fill_dimension_1" = "keys"."_fill_dimension_1"
      AND "_unfilled"."channel" IS NOT DISTINCT FROM "keys"."channel"
  ) AS "filled"
) AS "grouped"
GROUP BY
  "grouped"."channel"
HAVING
  NOT MAX("grouped"."_rows") IS NULL
```

The largest drop in revenue from one day to the next. Inside the filled `PER`, `LAG` reads the calendar day before, so a day without orders after a busy day is a drop to 0, not skipped.

## In constellations

A constellation's metrics can use `PER`, by its roles.

```yaml
constellations:
  - name: finance
    metrics:
      - name: avg_margin_per_customer
        expr: AVG(AGG(margin) PER (customer.id))
```

Input SQL:

```sql
SELECT
  customer.channel,
  AGG(avg_margin_per_customer)
FROM finance
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."channel" AS "channel",
  AVG("grouped"."avg_margin_per_customer") AS "avg_margin_per_customer"
FROM (
  SELECT
    COALESCE("orders"."customer_channel", "shipments"."customer_channel") AS "channel",
    COALESCE(MAX("orders"."revenue"), 0) - COALESCE(MAX("shipments"."cost"), 0) AS "avg_margin_per_customer"
  FROM (
    SELECT
      "customer"."channel" AS "customer_channel",
      "orders"."customer_id" AS "customer_id",
      SUM((
        "orders"."gross" - "orders"."discount"
      )) AS "revenue"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "marketing"."acquisition" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      "customer"."channel",
      "orders"."customer_id"
  ) AS "orders"
  FULL OUTER JOIN (
    SELECT
      "shipped_to"."channel" AS "customer_channel",
      "shipments"."customer_id" AS "customer_id",
      SUM("shipments"."shipping") AS "cost"
    FROM "operations"."shipments" AS "shipments"
    LEFT JOIN "marketing"."acquisition" AS "shipped_to"
      ON "shipped_to"."customer_id" = "shipments"."customer_id"
    GROUP BY
      "shipped_to"."channel",
      "shipments"."customer_id"
  ) AS "shipments"
    ON "shipments"."customer_channel" = "orders"."customer_channel"
    AND "shipments"."customer_id" = "orders"."customer_id"
  GROUP BY
    COALESCE("orders"."customer_channel", "shipments"."customer_channel"),
    COALESCE("orders"."customer_id", "shipments"."customer_id")
) AS "grouped"
GROUP BY
  "grouped"."channel"
```

`margin` spans orders and shipments, so each customer's margin is computed from both, joined on their roles, then averaged per channel.
A `PER` over a metric of a single dataset is computed within that dataset.

On a constellation, a window can only go inside a `PER`.
A window over a constellation's metrics, at the query's grain, isn't supported yet.

See [Constellations](/metricflow/constellations) for how they're defined.

## In regular tables

`PER` works on any table, not only datasets.
This is `avg_revenue_per_customer`, from above, written directly over the orders table:

```sql
SELECT
  DATE_TRUNC('month', sold_at) AS month,
  AVG(SUM(gross - discount) PER (customer_id)) AS avg_revenue_per_customer
FROM shop.orders
GROUP BY ALL
```

# Access

> Control who can query each dataset, entity, constellation and field with dbt platform groups.

MetricFlow supports access control through
[dbt platform groups](https://docs.getdbt.com/docs/platform/manage-access/about-user-access#groups).

Groups let you control who can query each object, and set mandatory filters and masks on data.

## Permissions

Add `permissions` to a dataset, entity, constellation or field (column, metric, etc.) to choose
which groups can use it.

```yaml
datasets:
  - name: raw_orders
    permissions:
      - groups: [finance_team]
```

Only `finance_team` can use `raw_orders`. Use `groups: ['*']` to open an object to everyone.

Objects inherit the permissions of the objects they read:

```yaml
constellations:
  - name: revenue_metrics
    metrics:
      - name: revenue
        expr: AGG(raw_orders.revenue)
```

Running `SELECT AGG(revenue) FROM revenue_metrics` needs access to `raw_orders`.

Add permissions to the constellation to override them:

```yaml
constellations:
  - name: revenue_metrics
    permissions:
      - groups: [finance_team, sales_team]
```

This replaces all inherited permissions, including [`where`](#rows) and [`mask`](#masking).
`sales_team` can now query revenue, even though it can't query `raw_orders`.

Fields can have permissions too:

```yaml
    metrics:
      - name: discounts
        expr: AGG(raw_orders.discounts)
        permissions:
          - groups: [finance_team]
```

To use a field, a group needs access to both the field and its object, so only `finance_team` can
use `discounts`. `SELECT *` leaves out fields the group can't use.

Entities work the same way:

```yaml
entities:
  - name: customer
    permissions:
      - groups: [finance_team]
```

`SELECT customer.plan, AGG(revenue) FROM revenue_metrics GROUP BY ALL` fails for `sales_team`,
because `plan` belongs to `customer`, which has its own permissions.

Objects a group can't use appear in metadata as inaccessible.

## Rows

Add `where` to a permission to filter the rows a group can see.

```yaml
datasets:
  - name: raw_orders
    permissions:
      - groups: [finance_team]
      - groups: [sales_team]
        where: region = 'NA'
```

`finance_team` can see every order, and `sales_team` can only see orders in NA. For
`sales_team`, totals like `AGG(revenue)` only add up NA orders.

Permissions are checked in order, and the first one that lists any of a user's groups is used, so
someone in both `finance_team` and `sales_team` can see every order.

## Aggregates

Add `having` to a permission to filter query results after aggregating. Like in SQL, `where` filters
rows before aggregating, and `having` filters the aggregated results.

```yaml
datasets:
  - name: raw_orders
    permissions:
      - groups: [sales_team]
        having: BOOL_AND(region = 'NA') OR COUNT(DISTINCT customer_id) FILTER (WHERE region <> 'NA') > 3
```

`sales_team` can see:

- NA orders, and totals made only from NA orders
- totals that include more than 3 customers outside NA

`SELECT * FROM raw_orders` returns only NA orders.

## Masking

Add `mask` to a field's permission to mask its value for a group.

```yaml
datasets:
  - name: raw_orders
    source:
      location: shop.orders
      columns:
        - name: customer_email
          permissions:
            - groups: [finance_team]
            - groups: [sales_team]
              mask: CONCAT(LEFT(customer_email, 1), '***')
```

`finance_team` can see the full email, and `sales_team` can only see its first
letter, like `j***`. The masked value is used everywhere in the query, including in `WHERE` and
`GROUP BY`.

In dbt, a mask can call one of the project's [macros](/metricflow/integrations/dbt#macros), like
`mask: "{{ email_mask('customer_email') }}"`.

## Policies

To reuse permissions, define a policy and reference it with `policy`:

```yaml
policies:
  - name: pii
    permissions:
      - groups: [finance_team]
      - groups: [sales_team]
        mask: '***'

datasets:
  - name: raw_orders
    source:
      location: shop.orders
      columns:
        - name: customer_email
          policy: pii
        - name: customer_phone
          policy: pii
```

`customer_email` and `customer_phone` get the same permissions. An object or field can't have both
`policy` and `permissions`.

## Source tables

Once a dataset reads a table, the table can only be queried through the dataset.

```yaml
datasets:
  - name: raw_orders
    source:
      location: shop.orders
    permissions:
      - groups: [finance_team]
```

`finance_team` has to query `raw_orders` to read `shop.orders`.

Any other dataset that reads `shop.orders` must set explicit permissions, to prevent accidentally
exposing data. Other tables have the same access as the [login](/metricflow/dbt-platform-setup) mapped to
the user's dbt platform group.

In dbt, you can also add `permissions` to a model in `schema.yml`:

```yaml
models:
  - name: raw_orders
    permissions:
      - groups: [finance_team]
```

# Common patterns

> Short, task-focused answers to specific modeling questions.

Here is how to implement some common data modeling patterns in MetricFlow.

## Schemas

### Star schema

A star schema has a fact table and many-to-one relationships dimension tables.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: customer_id
        - name: product_id
        - name: sold_at
        - name: amount
    key: [order_id]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: customer
        target: customers
        key: [{ name: customer_id, expr: customer_id }]
      - name: product
        target: products
        key: [{ name: product_id, expr: product_id }]
      - name: sold_on
        target: calendar
        key: [{ name: day, expr: CAST(sold_at AS DATE) }]
  - name: customers
    source:
      location: shop.customers
      columns:
        - name: customer_id
        - name: segment
    key: [customer_id]
  - name: products
    source:
      location: shop.products
      columns:
        - name: product_id
        - name: category
    key: [product_id]
  - name: calendar
    source:
      location: shop.calendar
      columns:
        - name: day
    key: [day]
    calculations:
      - name: month
        expr: DATE_TRUNC('month', day)
```

Input SQL:

```sql
SELECT
  sold_on.month,
  customer.segment,
  product.category,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  DATE_TRUNC('MONTH', "sold_on"."day") AS "month",
  "customer"."segment" AS "segment",
  "product"."category" AS "category",
  SUM("orders"."amount") AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."calendar" AS "sold_on"
  ON "sold_on"."day" = CAST("orders"."sold_at" AS DATE)
LEFT JOIN "shop"."customers" AS "customer"
  ON "customer"."customer_id" = "orders"."customer_id"
LEFT JOIN "shop"."products" AS "product"
  ON "product"."product_id" = "orders"."product_id"
GROUP BY
  DATE_TRUNC('MONTH', "sold_on"."day"),
  "customer"."segment",
  "product"."category"
```

Each dimension is a relationship from the fact.

A query only joins the dimensions it uses.

See [Relationships](/metricflow/datasets#relationships).

### Snowflake schema

A snowflake schema splits dimensions into more tables, e.g. products into products and categories.
Here, `orders` reaches `categories` through `products`.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: product_id
        - name: amount
    key: [order_id]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: product
        target: products
        key: [{ name: product_id, expr: product_id }]
  - name: products
    source:
      location: shop.products
      columns:
        - name: product_id
        - name: name
        - name: category_id
    key: [product_id]
    relationships:
      - name: category
        target: categories
        key: [{ name: category_id, expr: category_id }]
  - name: categories
    source:
      location: shop.categories
      columns:
        - name: category_id
        - name: name
        - name: department
    key: [category_id]
```

Input SQL:

```sql
SELECT
  product.category.department,
  product.category.name AS category,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "product_category"."department" AS "department",
  "product_category"."name" AS "category",
  SUM("orders"."amount") AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."products" AS "product"
  ON "product"."product_id" = "orders"."product_id"
LEFT JOIN "shop"."categories" AS "product_category"
  ON "product_category"."category_id" = "product"."category_id"
GROUP BY
  "product_category"."department",
  "product_category"."name"
```

A dimension can have relationships of its own.

A query follows them by name, e.g. `product.category.department`.

See [Multi-hop joins](/metricflow/datasets#multi-hop-joins).

### Galaxy schema

A galaxy schema, or fact constellation, has several fact tables that share dimensions.
This is exactly what Constellations are meant for.

```yaml
constellations:
  - name: sales
    metrics:
      - name: revenue
        expr: AGG(orders.revenue)
      - name: refunded
        expr: AGG(returns.refunded)
      - name: refund_rate
        expr: AGG(refunded) / AGG(revenue)
    roles:
      - name: customer
        datatype: REF(customers)
      - name: day
        datatype: DATE
    facts:
      - dataset: orders
        roles:
          - { name: customer, expr: customer }
          - { name: day, expr: CAST(sold_at AS DATE) }
      - dataset: returns
        roles:
          - { name: customer, expr: customer }
          - { name: day, expr: CAST(returned_at AS DATE) }
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: customer_id
        - name: sold_at
        - name: amount
    key: [order_id]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: customer
        target: customers
        key: [{ name: customer_id, expr: customer_id }]
  - name: returns
    source:
      location: shop.returns
      columns:
        - name: return_id
        - name: customer_id
        - name: returned_at
        - name: amount
    key: [return_id]
    calculations:
      - name: refunded
        expr: SUM(amount)
    relationships:
      - name: customer
        target: customers
        key: [{ name: customer_id, expr: customer_id }]
  - name: customers
    source:
      location: shop.customers
      columns:
        - name: customer_id
        - name: segment
    key: [customer_id]
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', day) AS month,
  customer.segment,
  AGG(revenue),
  AGG(refund_rate)
FROM sales
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "sales"."month" AS "month",
  "sales"."customer_segment" AS "segment",
  "sales"."revenue" AS "revenue",
  "sales"."refunded" / NULLIF("sales"."revenue", 0) AS "refund_rate"
FROM (
  SELECT
    COALESCE("orders"."month", "returns"."month") AS "month",
    COALESCE("orders"."customer_segment", "returns"."customer_segment") AS "customer_segment",
    MAX("orders"."revenue") AS "revenue",
    MAX("returns"."refunded") AS "refunded"
  FROM (
    SELECT
      CAST(DATE_TRUNC('MONTH', CAST("orders"."sold_at" AS DATE)) AS DATE) AS "month",
      "customer"."segment" AS "customer_segment",
      SUM("orders"."amount") AS "revenue"
    FROM "shop"."orders" AS "orders"
    LEFT JOIN "shop"."customers" AS "customer"
      ON "customer"."customer_id" = "orders"."customer_id"
    GROUP BY
      CAST(DATE_TRUNC('MONTH', CAST("orders"."sold_at" AS DATE)) AS DATE),
      "customer"."segment"
  ) AS "orders"
  FULL OUTER JOIN (
    SELECT
      CAST(DATE_TRUNC('MONTH', CAST("returns"."returned_at" AS DATE)) AS DATE) AS "month",
      "customer"."segment" AS "customer_segment",
      SUM("returns"."amount") AS "refunded"
    FROM "shop"."returns" AS "returns"
    LEFT JOIN "shop"."customers" AS "customer"
      ON "customer"."customer_id" = "returns"."customer_id"
    GROUP BY
      CAST(DATE_TRUNC('MONTH', CAST("returns"."returned_at" AS DATE)) AS DATE),
      "customer"."segment"
  ) AS "returns"
    ON "returns"."month" = "orders"."month"
    AND "returns"."customer_segment" = "orders"."customer_segment"
  GROUP BY
    COALESCE("orders"."month", "returns"."month"),
    COALESCE("orders"."customer_segment", "returns"."customer_segment")
) AS "sales"
```

Metrics can combine facts.

Each shared dimension is a role, so a query can group both facts by `customer.segment`.

Each fact is aggregated on its own, then joined on the roles, so neither fact is repeated by the other.

See [Constellations](/metricflow/constellations).

### Data Vault

In a Data Vault, a hub holds a business key, and satellites hold its attributes, often from different systems.
An entity models a hub: its key is the hub's key, and each satellite is a source.

```yaml
entities:
  - name: customer
    key:
      - name: id
        datatype: VARCHAR
      - name: as_of
        datatype: TIMESTAMP
    sources:
      - dataset: sat_customer_profile
        on: customer_key = :id AND :as_of >= load_start AND (load_end IS NULL OR :as_of < load_end)
      - dataset: sat_customer_billing
        on: customer_key = :id AND :as_of >= load_start AND (load_end IS NULL OR :as_of < load_end)
    attributes:
      - name: segment
        expr: sat_customer_profile.segment
      - name: plan
        expr: sat_customer_billing.plan
datasets:
  - name: sat_customer_profile
    source:
      location: vault.sat_customer_profile
      columns:
        - name: customer_key
        - name: segment
        - name: load_start
        - name: load_end
    key:
      - customer_key
      - on: :as_of >= load_start AND (load_end IS NULL OR :as_of < load_end)
  - name: sat_customer_billing
    source:
      location: vault.sat_customer_billing
      columns:
        - name: customer_key
        - name: plan
        - name: load_start
        - name: load_end
    key:
      - customer_key
      - on: :as_of >= load_start AND (load_end IS NULL OR :as_of < load_end)
  - name: orders
    source:
      location: vault.sat_order
      columns:
        - name: order_key
        - name: customer_key
        - name: amount
        - name: sold_at
    key: [order_key]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: customer
        target: customer
        key:
          - { name: id, expr: customer_key }
          - { name: as_of, expr: sold_at }
```

Input SQL:

```sql
SELECT
  customer.segment,
  customer.plan,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "customer"."segment" AS "segment",
  "customer_2"."plan" AS "plan",
  SUM("orders"."amount") AS "revenue"
FROM "vault"."sat_order" AS "orders"
LEFT JOIN "vault"."sat_customer_profile" AS "customer"
  ON "customer"."customer_key" = "orders"."customer_key"
  AND "orders"."sold_at" >= "customer"."load_start"
  AND (
    "customer"."load_end" IS NULL OR "orders"."sold_at" < "customer"."load_end"
  )
LEFT JOIN "vault"."sat_customer_billing" AS "customer_2"
  ON "customer_2"."customer_key" = "orders"."customer_key"
  AND "orders"."sold_at" >= "customer_2"."load_start"
  AND (
    "customer_2"."load_end" IS NULL OR "orders"."sold_at" < "customer_2"."load_end"
  )
GROUP BY
  "customer"."segment",
  "customer_2"."plan"
```

Satellites keep a row per change, so the entity's key includes a point in time, `as_of`.

Each source picks the satellite row valid at `:as_of`.

The satellite's key says the same: one row per customer at a time.

Orders pass their own time, so each order reads the customer as of the sale. Pass `CURRENT_TIMESTAMP` for the current version.

This is the same pattern as [SCD Type 2 dimensions](#scd-type-2-dimensions).

See [Entities](/metricflow/entities).

## Relationships

### Role-playing dimensions

The same dataset or entity can play several roles, e.g. a user is the buyer of one sale and the seller of another.

```yaml
datasets:
  - name: sales
    source:
      location: market.sales
      columns:
        - name: sale_id
        - name: buyer_id
        - name: seller_id
        - name: amount
    key: [sale_id]
    calculations:
      - name: gmv
        expr: SUM(amount)
      - name: is_cross_border
        expr: buyer.country <> seller.country
    relationships:
      - name: buyer
        target: users
        key: [{ name: user_id, expr: buyer_id }]
      - name: seller
        target: users
        key: [{ name: user_id, expr: seller_id }]
  - name: users
    source:
      location: market.users
      columns:
        - name: user_id
        - name: country
    key: [user_id]
```

Input SQL:

```sql
SELECT
  buyer.country AS buyer_country,
  seller.country AS seller_country,
  AGG(gmv)
FROM sales
WHERE is_cross_border
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "buyer"."country" AS "buyer_country",
  "seller"."country" AS "seller_country",
  SUM("sales"."amount") AS "gmv"
FROM "market"."sales" AS "sales"
LEFT JOIN "market"."users" AS "buyer"
  ON "buyer"."user_id" = "sales"."buyer_id"
LEFT JOIN "market"."users" AS "seller"
  ON "seller"."user_id" = "sales"."seller_id"
WHERE
  "buyer"."country" <> "seller"."country"
GROUP BY
  "buyer"."country",
  "seller"."country"
```

Each role is its own relationship, with its own name. No copy of `users` is needed.

Constellation roles work the same way: two roles can reference the same dataset or entity.

```yaml
constellations:
  - name: trades
    metrics:
      - name: gmv
        expr: AGG(sales.gmv)
      - name: return_rate
        expr: AGG(returns.returned) / AGG(gmv)
    roles:
      - name: buyer
        datatype: REF(users)
      - name: seller
        datatype: REF(users)
    facts:
      - dataset: sales
        roles:
          - { name: buyer, expr: buyer }
          - { name: seller, expr: seller }
      - dataset: returns
        roles:
          - { name: buyer, expr: customer }
          - { name: seller, expr: merchant }
datasets:
  - name: returns
    source:
      location: market.returns
      columns:
        - name: return_id
        - name: buyer_id
        - name: seller_id
        - name: amount
    key: [return_id]
    calculations:
      - name: returned
        expr: SUM(amount)
    relationships:
      - name: customer
        target: users
        key: [{ name: user_id, expr: buyer_id }]
      - name: merchant
        target: users
        key: [{ name: user_id, expr: seller_id }]
```

Input SQL:

```sql
SELECT
  buyer.country AS buyer_country,
  seller.country AS seller_country,
  AGG(gmv),
  AGG(return_rate)
FROM trades
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "trades"."buyer_country" AS "buyer_country",
  "trades"."seller_country" AS "seller_country",
  "trades"."gmv" AS "gmv",
  "trades"."returned" / NULLIF("trades"."gmv", 0) AS "return_rate"
FROM (
  SELECT
    COALESCE("sales"."buyer_country", "returns"."buyer_country") AS "buyer_country",
    COALESCE("sales"."seller_country", "returns"."seller_country") AS "seller_country",
    MAX("sales"."gmv") AS "gmv",
    MAX("returns"."returned") AS "returned"
  FROM (
    SELECT
      "buyer"."country" AS "buyer_country",
      "seller"."country" AS "seller_country",
      SUM("sales"."amount") AS "gmv"
    FROM "market"."sales" AS "sales"
    LEFT JOIN "market"."users" AS "buyer"
      ON "buyer"."user_id" = "sales"."buyer_id"
    LEFT JOIN "market"."users" AS "seller"
      ON "seller"."user_id" = "sales"."seller_id"
    GROUP BY
      "buyer"."country",
      "seller"."country"
  ) AS "sales"
  FULL OUTER JOIN (
    SELECT
      "customer"."country" AS "buyer_country",
      "merchant"."country" AS "seller_country",
      SUM("returns"."amount") AS "returned"
    FROM "market"."returns" AS "returns"
    LEFT JOIN "market"."users" AS "customer"
      ON "customer"."user_id" = "returns"."buyer_id"
    LEFT JOIN "market"."users" AS "merchant"
      ON "merchant"."user_id" = "returns"."seller_id"
    GROUP BY
      "customer"."country",
      "merchant"."country"
  ) AS "returns"
    ON "returns"."buyer_country" = "sales"."buyer_country"
    AND "returns"."seller_country" = "sales"."seller_country"
  GROUP BY
    COALESCE("sales"."buyer_country", "returns"."buyer_country"),
    COALESCE("sales"."seller_country", "returns"."seller_country")
) AS "trades"
```

Each role is typed as `REF(users)`.

Each fact maps the roles to its own relationships: `returns` calls the buyer `customer`, and the seller `merchant`.

See [Relationships](/metricflow/datasets#relationships) and [Constellations](/metricflow/constellations#roles).

### Role-playing facts

The same dataset can be a fact of a constellation more than once, each time with its own `alias` and roles.

```yaml
constellations:
  - name: marketplace
    metrics:
      - name: bought
        expr: AGG(purchases.gmv)
      - name: sold
        expr: AGG(sales.gmv)
      - name: net
        expr: AGG(sold) - AGG(bought)
    roles:
      - name: user
        datatype: REF(users)
    facts:
      - dataset: sales
        alias: purchases
        roles:
          - { name: user, expr: buyer }
      - dataset: sales
        roles:
          - { name: user, expr: seller }
datasets:
  - name: sales
    source:
      location: market.sales
      columns:
        - name: sale_id
        - name: buyer_id
        - name: seller_id
        - name: amount
    key: [sale_id]
    calculations:
      - name: gmv
        expr: SUM(amount)
    relationships:
      - name: buyer
        target: users
        key: [{ name: user_id, expr: buyer_id }]
      - name: seller
        target: users
        key: [{ name: user_id, expr: seller_id }]
```

Input SQL:

```sql
SELECT
  user.country,
  AGG(bought),
  AGG(sold),
  AGG(net)
FROM marketplace
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "marketplace"."user_country" AS "country",
  "marketplace"."gmv" AS "bought",
  "marketplace"."gmv_2" AS "sold",
  COALESCE("marketplace"."gmv_2", 0) - COALESCE("marketplace"."gmv", 0) AS "net"
FROM (
  SELECT
    COALESCE("purchases"."user_country", "sales"."user_country") AS "user_country",
    MAX("purchases"."gmv") AS "gmv",
    MAX("sales"."gmv_2") AS "gmv_2"
  FROM (
    SELECT
      "buyer"."country" AS "user_country",
      SUM("sales"."amount") AS "gmv"
    FROM "market"."sales" AS "sales"
    LEFT JOIN "market"."users" AS "buyer"
      ON "buyer"."user_id" = "sales"."buyer_id"
    GROUP BY
      "buyer"."country"
  ) AS "purchases"
  FULL OUTER JOIN (
    SELECT
      "seller"."country" AS "user_country",
      SUM("sales"."amount") AS "gmv_2"
    FROM "market"."sales" AS "sales"
    LEFT JOIN "market"."users" AS "seller"
      ON "seller"."user_id" = "sales"."seller_id"
    GROUP BY
      "seller"."country"
  ) AS "sales"
    ON "sales"."user_country" = "purchases"."user_country"
  GROUP BY
    COALESCE("purchases"."user_country", "sales"."user_country")
) AS "marketplace"
```

Metrics read a fact by its alias, which defaults to the dataset's name.

Each fact sets `user` to a different relationship, so grouping by `user.country` gives what each country bought and sold.

See [Constellations](/metricflow/constellations#facts).

### Many-to-many relationships

A bridge table links two datasets many-to-many.

```yaml
datasets:
  - name: accounts
    source:
      location: saas.accounts
      columns:
        - name: account_id
        - name: mrr
    key: [account_id]
    calculations:
      - name: total_mrr
        expr: SUM(mrr)
    relationships:
      - name: members
        target: account_users
        key: [{ name: account_id, expr: account_id }]
  - name: account_users
    source:
      location: saas.account_users
      columns:
        - name: account_id
        - name: user_id
    key: [account_id, user_id]
    relationships:
      - name: user
        target: users
        key: [{ name: user_id, expr: user_id }]
  - name: users
    source:
      location: saas.users
      columns:
        - name: user_id
        - name: country
    key: [user_id]
```

Input SQL:

```sql
SELECT
  members.user.country,
  AGG(total_mrr)
FROM accounts
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."country" AS "country",
  SUM("grouped"."total_mrr") AS "total_mrr"
FROM (
  SELECT
    "members_user"."country" AS "country",
    ANY_VALUE("accounts"."mrr") AS "total_mrr"
  FROM "saas"."accounts" AS "accounts"
  LEFT JOIN "saas"."account_users" AS "members"
    ON "members"."account_id" = "accounts"."account_id"
  LEFT JOIN "saas"."users" AS "members_user"
    ON "members_user"."user_id" = "members"."user_id"
  GROUP BY
    "members_user"."country",
    "accounts"."account_id"
) AS "grouped"
GROUP BY
  "grouped"."country"
```

`members` binds only `account_id`, part of the bridge's key, so it's one-to-many.

`user` is many-to-one, so `members.user.country` reads like any field.

Fan-out protection counts each account's `mrr` once per country, however many users it has there.
An account with users in two countries is in both countries' totals, so the countries' totals can sum to more than the overall total.

See [One-to-many relationships](/metricflow/datasets#one-to-many-relationships).

### Relationship keys that depend on other relationships

A relationship's key can read another relationship's fields.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: product_id
        - name: store_id
        - name: quantity
    key: [order_id]
    relationships:
      - name: store
        target: stores
        key: [{ name: store_id, expr: store_id }]
      - name: price
        target: regional_prices
        key:
          - { name: product_id, expr: product_id }
          - { name: region_id, expr: store.region_id }
    calculations:
      - name: revenue
        expr: SUM(quantity * price.unit_price)
  - name: stores
    source:
      location: shop.stores
      columns:
        - name: store_id
        - name: region_id
    key: [store_id]
  - name: regional_prices
    source:
      location: shop.regional_prices
      columns:
        - name: product_id
        - name: region_id
        - name: unit_price
    key: [product_id, region_id]
```

Input SQL:

```sql
SELECT
  price.region_id,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "price"."region_id" AS "region_id",
  SUM("orders"."quantity" * "price"."unit_price") AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."stores" AS "store"
  ON "store"."store_id" = "orders"."store_id"
LEFT JOIN "shop"."regional_prices" AS "price"
  ON "price"."product_id" = "orders"."product_id"
  AND "price"."region_id" = "store"."region_id"
GROUP BY
  "price"."region_id"
```

The key reads `store.region_id`, so `stores` is joined first.

Then `price` works like any other relationship.

### Entity-attribute-value tables

An entity-attribute-value (EAV) table has a row per attribute, instead of a column per attribute.
Here, `user_attributes` holds each user's `plan` and `industry`.

```yaml
datasets:
  - name: users
    source:
      location: app.users
      columns:
        - name: user_id
    key: [user_id]
    calculations:
      - name: plan
        expr: plan_attribute.value
      - name: industry
        expr: industry_attribute.value
      - name: user_count
        expr: COUNT(*)
    relationships:
      - name: plan_attribute
        target: user_attributes
        key:
          - { name: user_id, expr: user_id }
          - { name: attribute, expr: "'plan'" }
      - name: industry_attribute
        target: user_attributes
        key:
          - { name: user_id, expr: user_id }
          - { name: attribute, expr: "'industry'" }
  - name: user_attributes
    source:
      location: app.user_attributes
      columns:
        - name: user_id
        - name: attribute
        - name: value
    key: [user_id, attribute]
```

Input SQL:

```sql
SELECT
  plan,
  industry,
  AGG(user_count)
FROM users
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "plan_attribute"."value" AS "plan",
  "industry_attribute"."value" AS "industry",
  COUNT(*) AS "user_count"
FROM "app"."users" AS "users"
LEFT JOIN "app"."user_attributes" AS "plan_attribute"
  ON "plan_attribute"."user_id" = "users"."user_id"
  AND "plan_attribute"."attribute" = 'plan'
LEFT JOIN "app"."user_attributes" AS "industry_attribute"
  ON "industry_attribute"."user_id" = "users"."user_id"
  AND "industry_attribute"."attribute" = 'industry'
GROUP BY
  "plan_attribute"."value",
  "industry_attribute"."value"
```

A calculation per attribute turns it into a column of `users`.

Each relationship sets `attribute` to a constant.

With `user_id`, that's the whole key, so each relationship joins at most one row.

A query only joins the attributes it uses. Cast values as needed, e.g. `CAST(seats_attribute.value AS INT)`.

See [Relationships](/metricflow/datasets#relationships).

### SCD Type 2 dimensions

A slowly changing dimension (SCD Type 2) keeps a row per version, each valid for a period.

```yaml
datasets:
  - name: plan_history
    source:
      location: shop.plan_history
      columns:
        - name: customer_id
        - name: plan
        - name: valid_from
        - name: valid_to
    key:
      - customer_id
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: customer_id
        - name: amount
        - name: sold_at
    key: [order_id]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: plan_at_sale
        target: plan_history
        key:
          - { name: customer_id, expr: customer_id }
          - { name: as_of, expr: sold_at }
      - name: current_plan
        target: plan_history
        key:
          - { name: customer_id, expr: customer_id }
          - { name: as_of, expr: CURRENT_TIMESTAMP }
```

Input SQL:

```sql
SELECT
  plan_at_sale.plan AS plan_at_sale,
  current_plan.plan AS current_plan,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "plan_at_sale"."plan" AS "plan_at_sale",
  "current_plan"."plan" AS "current_plan",
  SUM("orders"."amount") AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."plan_history" AS "plan_at_sale"
  ON "plan_at_sale"."customer_id" = "orders"."customer_id"
  AND (
    "orders"."sold_at" >= "plan_at_sale"."valid_from"
    AND (
      "plan_at_sale"."valid_to" IS NULL
      OR "orders"."sold_at" < "plan_at_sale"."valid_to"
    )
  )
LEFT JOIN "shop"."plan_history" AS "current_plan"
  ON "current_plan"."customer_id" = "orders"."customer_id"
  AND (
    CURRENT_TIMESTAMP >= "current_plan"."valid_from"
    AND (
      "current_plan"."valid_to" IS NULL
      OR CURRENT_TIMESTAMP < "current_plan"."valid_to"
    )
  )
GROUP BY
  "plan_at_sale"."plan",
  "current_plan"."plan"
```

The key is `customer_id` and a condition on `:as_of`, so together they pick one version.

Setting `as_of` to `sold_at` gives the plan at the time of the sale.

Setting it to `CURRENT_TIMESTAMP` gives the current plan. A query can group by either or both.

See [Key conditions](/metricflow/datasets#key-conditions).

### Propagating time through relationships

A key parameter can pass through a chain of relationships. Here, a time parameter is passed through
a chain of SCD2 dimensions, so each is joined at the point of time of the root table.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: customer_id
        - name: amount
        - name: sold_at
    key: [order_id]
    calculations:
      - name: revenue
        expr: SUM(amount)
    relationships:
      - name: customer
        target: customer_history
        key:
          - { name: customer_id, expr: customer_id }
          - { name: as_of, expr: sold_at }
  - name: customer_history
    source:
      location: crm.customer_history
      columns:
        - name: customer_id
        - name: account_id
        - name: valid_from
        - name: valid_to
    key:
      - customer_id
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
    relationships:
      - name: account
        target: account_history
        key:
          - { name: account_id, expr: account_id }
          - { name: as_of, expr: ":as_of" }
  - name: account_history
    source:
      location: crm.account_history
      columns:
        - name: account_id
        - name: segment
        - name: owner_id
        - name: valid_from
        - name: valid_to
    key:
      - account_id
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
    relationships:
      - name: owner
        target: rep_history
        key:
          - { name: rep_id, expr: owner_id }
          - { name: as_of, expr: ":as_of" }
  - name: rep_history
    source:
      location: crm.rep_history
      columns:
        - name: rep_id
        - name: team
        - name: valid_from
        - name: valid_to
    key:
      - rep_id
      - on: :as_of >= valid_from AND (valid_to IS NULL OR :as_of < valid_to)
```

Input SQL:

```sql
SELECT
  customer.account.segment,
  customer.account.owner.team,
  AGG(revenue)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "customer_account"."segment" AS "segment",
  "customer_account_owner"."team" AS "team",
  SUM("orders"."amount") AS "revenue"
FROM "shop"."orders" AS "orders"
LEFT JOIN "crm"."customer_history" AS "customer"
  ON "customer"."customer_id" = "orders"."customer_id"
  AND (
    "orders"."sold_at" >= "customer"."valid_from"
    AND (
      "customer"."valid_to" IS NULL OR "orders"."sold_at" < "customer"."valid_to"
    )
  )
LEFT JOIN "crm"."account_history" AS "customer_account"
  ON "customer_account"."account_id" = "customer"."account_id"
  AND (
    "orders"."sold_at" >= "customer_account"."valid_from"
    AND (
      "customer_account"."valid_to" IS NULL
      OR "orders"."sold_at" < "customer_account"."valid_to"
    )
  )
LEFT JOIN "crm"."rep_history" AS "customer_account_owner"
  ON "customer_account_owner"."rep_id" = "customer_account"."owner_id"
  AND (
    "orders"."sold_at" >= "customer_account_owner"."valid_from"
    AND (
      "customer_account_owner"."valid_to" IS NULL
      OR "orders"."sold_at" < "customer_account_owner"."valid_to"
    )
  )
GROUP BY
  "customer_account"."segment",
  "customer_account_owner"."team"
```

Orders set `as_of` to `sold_at`.

Each relationship passes on the `:as_of` it received, so the account and rep are also the ones at the time of the sale.

Another dataset, e.g. shipments, can use the same chain with its own time, e.g. `shipped_at`.

See [Multi-hop joins](/metricflow/datasets#multi-hop-joins).

### Fiscal and retail calendars

Report by fiscal year and period, e.g. a retail 4-5-4 calendar.
Here, `fiscal_calendar` has a row per day, with its fiscal year, quarter and period.

```yaml
datasets:
  - name: fiscal_calendar
    source:
      location: finance.fiscal_calendar
      columns:
        - name: day
        - name: fiscal_year
        - name: fiscal_quarter
        - name: fiscal_period
    key: [day]
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: amount
        - name: sold_at
    key: [order_id]
    relationships:
      - name: sold_on
        target: fiscal_calendar
        key: [{ name: day, expr: CAST(sold_at AS DATE) }]
        always_matches: true
    calculations:
      - name: revenue
        expr: SUM(amount)
      - name: revenue_last_fiscal_year
        expr: >-
          LAG(AGG(revenue)) OVER (
            PARTITION BY EXCLUDING sold_on.fiscal_year
            ORDER BY sold_on.fiscal_year
          )
```

Input SQL:

```sql
SELECT
  sold_on.fiscal_year,
  sold_on.fiscal_period,
  AGG(revenue),
  AGG(revenue_last_fiscal_year)
FROM orders
WHERE sold_on.fiscal_year = 2025
GROUP BY ALL
ORDER BY sold_on.fiscal_period
```

Compiled SQL:

```sql
SELECT
  "orders"."fiscal_year" AS "fiscal_year",
  "orders"."fiscal_period" AS "fiscal_period",
  "orders"."revenue" AS "revenue",
  "orders"."revenue_last_fiscal_year" AS "revenue_last_fiscal_year"
FROM (
  SELECT
    "windowed"."fiscal_year" AS "fiscal_year",
    "windowed"."fiscal_period" AS "fiscal_period",
    "windowed"."revenue" AS "revenue",
    "windowed"."revenue_last_fiscal_year" AS "revenue_last_fiscal_year"
  FROM (
    SELECT
      "aggregated"."fiscal_year" AS "fiscal_year",
      "aggregated"."fiscal_period" AS "fiscal_period",
      "aggregated"."revenue" AS "revenue",
      LAG("aggregated"."revenue") OVER (PARTITION BY "aggregated"."fiscal_period" ORDER BY "aggregated"."fiscal_year") AS "revenue_last_fiscal_year"
    FROM (
      SELECT
        "sold_on"."fiscal_year" AS "fiscal_year",
        "sold_on"."fiscal_period" AS "fiscal_period",
        SUM("orders"."amount") AS "revenue"
      FROM "shop"."orders" AS "orders"
      LEFT JOIN "finance"."fiscal_calendar" AS "sold_on"
        ON "sold_on"."day" = CAST("orders"."sold_at" AS DATE)
      GROUP BY
        "sold_on"."fiscal_year",
        "sold_on"."fiscal_period"
    ) AS "aggregated"
  ) AS "windowed"
  WHERE
    "windowed"."fiscal_year" = 2025
) AS "orders"
ORDER BY
  "fiscal_period"
```

The fiscal rules live in one table, not in date math in every query.

Orders join it by day, so queries can group by any fiscal column.

The window is partitioned by period and ordered by year, so `LAG` reads the same period last year.

This filter applies after the window, so 2025 still reads 2024.

See [Window functions: `OVER`](/metricflow/complex-metrics#window-functions-over).

## Metrics

### Filtered metrics

A filtered metric aggregates only some rows.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: customer_id
        - name: amount
        - name: status
        - name: sold_at
    key: [order_id]
    relationships:
      - name: customer
        target: customers
        key: [{ name: customer_id, expr: customer_id }]
    calculations:
      - name: revenue
        expr: SUM(amount)
      - name: refunded_revenue
        expr: SUM(amount) FILTER (WHERE status = 'refunded')
      - name: refund_rate
        expr: AGG(refunded_revenue) / AGG(revenue)
      - name: enterprise_revenue
        expr: SUM(amount) FILTER (WHERE customer.segment = 'enterprise')
      - name: new_customer_revenue
        expr: SUM(CASE WHEN sold_at < customer.signed_up_at + INTERVAL 30 DAY THEN amount END)
  - name: customers
    source:
      location: shop.customers
      columns:
        - name: customer_id
        - name: segment
        - name: signed_up_at
    key: [customer_id]
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', sold_at) AS month,
  AGG(revenue),
  AGG(refund_rate),
  AGG(enterprise_revenue),
  AGG(new_customer_revenue),
  AGG(refund_rate) FILTER (WHERE customer.segment = 'enterprise') AS enterprise_refund_rate
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  DATE_TRUNC('MONTH', "orders"."sold_at") AS "month",
  SUM("orders"."amount") AS "revenue",
  SUM("orders"."amount") FILTER(WHERE
    "orders"."status" = 'refunded') / SUM("orders"."amount") AS "refund_rate",
  SUM("orders"."amount") FILTER(WHERE
    "customer"."segment" = 'enterprise') AS "enterprise_revenue",
  SUM(
    CASE
      WHEN "orders"."sold_at" < "customer"."signed_up_at" + INTERVAL '30' DAY
      THEN "orders"."amount"
    END
  ) AS "new_customer_revenue",
  SUM("orders"."amount") FILTER(WHERE
    "orders"."status" = 'refunded' AND "customer"."segment" = 'enterprise') / SUM("orders"."amount") FILTER(WHERE
    "customer"."segment" = 'enterprise') AS "enterprise_refund_rate"
FROM "shop"."orders" AS "orders"
LEFT JOIN "shop"."customers" AS "customer"
  ON "customer"."customer_id" = "orders"."customer_id"
GROUP BY
  DATE_TRUNC('MONTH', "orders"."sold_at")
```

`FILTER (WHERE ...)` aggregates only matching rows.

A filter can read a relationship, like the customer's segment. MetricFlow adds the join.

`SUM(CASE ...)` also works, e.g. on warehouses without `FILTER`. Here, revenue in a customer's first 30 days.

A query can filter a calculation too. Here, both parts of `refund_rate` count enterprise customers only.

See [Predefined aggregations](/metricflow/reference/sql/extensions#predefined-aggregations).

### Share of a subtotal

A product's share of its category is its revenue divided by its category's.
`PARTITION BY EXCLUDING` names what to add up over, and keeps everything else the query groups by.

```yaml
datasets:
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: product_id
        - name: amount
        - name: sold_at
    key: [order_id]
    relationships:
      - name: product
        target: products
        key: [{ name: product_id, expr: product_id }]
    calculations:
      - name: revenue
        expr: SUM(amount)
      - name: share_of_category
        expr: AGG(revenue) / SUM(AGG(revenue)) OVER (PARTITION BY EXCLUDING product.name)
      - name: share_of_total
        expr: AGG(revenue) / SUM(AGG(revenue)) OVER (PARTITION BY EXCLUDING product.name, product.category)
  - name: products
    source:
      location: shop.products
      columns:
        - name: product_id
        - name: name
        - name: category
    key: [product_id]
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', sold_at) AS month,
  product.category,
  product.name,
  AGG(revenue),
  AGG(share_of_category),
  AGG(share_of_total)
FROM orders
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "aggregated"."month" AS "month",
  "aggregated"."category" AS "category",
  "aggregated"."name" AS "name",
  "aggregated"."revenue" AS "revenue",
  "aggregated"."revenue" / SUM("aggregated"."revenue") OVER (PARTITION BY "aggregated"."month", "aggregated"."category") AS "share_of_category",
  "aggregated"."revenue" / SUM("aggregated"."revenue") OVER (PARTITION BY "aggregated"."month") AS "share_of_total"
FROM (
  SELECT
    DATE_TRUNC('MONTH', "orders"."sold_at") AS "month",
    "product"."category" AS "category",
    "product"."name" AS "name",
    SUM("orders"."amount") AS "revenue"
  FROM "shop"."orders" AS "orders"
  LEFT JOIN "shop"."products" AS "product"
    ON "product"."product_id" = "orders"."product_id"
  GROUP BY
    DATE_TRUNC('MONTH', "orders"."sold_at"),
    "product"."category",
    "product"."name"
) AS "aggregated"
```

Adds up over products, keeping the category: each product's share of its category.

Adds up over categories too: each product's share of the total.
The query's other groups still apply, so here it's the share of each month's total.

See [Window functions](/metricflow/complex-metrics#window-functions-over).

### Semi-additive metrics

A balance is a snapshot. It can be added it up across accounts, but not over time.

```yaml
datasets:
  - name: balances
    source:
      location: finance.daily_balances
      columns:
        - name: account_id
        - name: balance_date
        - name: balance
    key: [account_id, balance_date]
    calculations:
      - name: closing_balance
        expr: MAX_BY(SUM(balance) PER (balance_date), balance_date)
      - name: last_balance_per_account
        expr: SUM(MAX_BY(balance, balance_date) PER (account_id))
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', balance_date) AS month,
  AGG(closing_balance),
  AGG(last_balance_per_account)
FROM balances
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."month" AS "month",
  ARG_MAX("grouped"."closing_balance", "grouped"."_per_column_1") FILTER(WHERE
    "grouped"."_group_id" = 1) AS "closing_balance",
  SUM("grouped"."last_balance_per_account") FILTER(WHERE
    "grouped"."_group_id" = 2) AS "last_balance_per_account"
FROM (
  SELECT
    DATE_TRUNC('MONTH', "balances"."balance_date") AS "month",
    "balances"."balance_date" AS "_per_column_1",
    SUM("balances"."balance") AS "closing_balance",
    ARG_MAX("balances"."balance", "balances"."balance_date") AS "last_balance_per_account",
    GROUPING("balances"."balance_date") * 2 + GROUPING("balances"."account_id") AS "_group_id"
  FROM "finance"."daily_balances" AS "balances"
  GROUP BY
    GROUPING SETS (
      (DATE_TRUNC('MONTH', "balances"."balance_date"), "balances"."balance_date"),
      (DATE_TRUNC('MONTH', "balances"."balance_date"), "balances"."account_id")
    )
) AS "grouped"
GROUP BY
  "grouped"."month"
```

The total on the period's last day: sum the accounts each day, then keep the last day.

Or, each account's latest balance in the period, summed.
This also counts accounts with no row on the last day, e.g. one closed mid-month.

See [Multi-level aggregation](/metricflow/complex-metrics#multi-level-aggregation-per).

### Ratios across two facts

A conversion rate divides orders by sessions, two datasets that can't be joined row by row.
A constellation aggregates each separately, then joins them on shared roles.

```yaml
constellations:
  - name: web_funnel
    metrics:
      - name: sessions
        expr: AGG(sessions.session_count)
      - name: orders
        expr: AGG(orders.order_count)
      - name: conversion_rate
        expr: COALESCE(AGG(orders), 0) / AGG(sessions)
      - name: revenue_per_session
        expr: COALESCE(AGG(orders.revenue), 0) / AGG(sessions)
    roles:
      - name: day
        datatype: DATE
      - name: channel
    facts:
      - dataset: sessions
        roles:
          - { name: day, expr: "CAST(started_at AS DATE)" }
          - { name: channel, expr: channel }
      - dataset: orders
        roles:
          - { name: day, expr: "CAST(sold_at AS DATE)" }
          - { name: channel, expr: channel }
datasets:
  - name: sessions
    source:
      location: web.sessions
      columns:
        - name: session_id
        - name: started_at
        - name: channel
    key: [session_id]
    calculations:
      - name: session_count
        expr: COUNT(*)
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: sold_at
        - name: channel
        - name: amount
    key: [order_id]
    calculations:
      - name: order_count
        expr: COUNT(*)
      - name: revenue
        expr: SUM(amount)
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('week', day) AS week,
  channel,
  AGG(conversion_rate),
  AGG(revenue_per_session)
FROM web_funnel
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "web_funnel"."week" AS "week",
  "web_funnel"."channel" AS "channel",
  COALESCE("web_funnel"."order_count", 0) / NULLIF("web_funnel"."session_count", 0) AS "conversion_rate",
  COALESCE("web_funnel"."revenue", 0) / NULLIF("web_funnel"."session_count", 0) AS "revenue_per_session"
FROM (
  SELECT
    COALESCE("orders"."week", "sessions"."week") AS "week",
    COALESCE("orders"."channel", "sessions"."channel") AS "channel",
    MAX("orders"."order_count") AS "order_count",
    MAX("sessions"."session_count") AS "session_count",
    MAX("orders"."revenue") AS "revenue"
  FROM (
    SELECT
      CAST(DATE_TRUNC('WEEK', CAST("orders"."sold_at" AS DATE)) AS DATE) AS "week",
      "orders"."channel" AS "channel",
      COUNT(*) AS "order_count",
      SUM("orders"."amount") AS "revenue"
    FROM "shop"."orders" AS "orders"
    GROUP BY
      CAST(DATE_TRUNC('WEEK', CAST("orders"."sold_at" AS DATE)) AS DATE),
      "orders"."channel"
  ) AS "orders"
  FULL OUTER JOIN (
    SELECT
      CAST(DATE_TRUNC('WEEK', CAST("sessions"."started_at" AS DATE)) AS DATE) AS "week",
      "sessions"."channel" AS "channel",
      COUNT(*) AS "session_count"
    FROM "web"."sessions" AS "sessions"
    GROUP BY
      CAST(DATE_TRUNC('WEEK', CAST("sessions"."started_at" AS DATE)) AS DATE),
      "sessions"."channel"
  ) AS "sessions"
    ON "sessions"."week" = "orders"."week" AND "sessions"."channel" = "orders"."channel"
  GROUP BY
    COALESCE("orders"."week", "sessions"."week"),
    COALESCE("orders"."channel", "sessions"."channel")
) AS "web_funnel"
```

A week with sessions but no orders has a NULL order count. `COALESCE` reports its rate as 0 instead.

Each fact maps its own time to `day`. Queries can group by any expression of it, e.g. the week.

See [Constellations](/metricflow/constellations).

### Average of per-entity totals

Some metrics require multiple stages of aggregation.

```yaml
datasets:
  - name: sales
    source:
      location: food.truck_sales
      columns:
        - name: sale_id
        - name: truck_id
        - name: sold_at
        - name: amount
    key: [sale_id]
    relationships:
      - name: truck
        target: trucks
        key: [{ name: truck_id, expr: truck_id }]
    calculations:
      - name: revenue
        expr: SUM(amount)
      - name: avg_daily_revenue_per_truck
        expr: AVG(AGG(revenue) PER (truck_id, CAST(sold_at AS DATE)))
  - name: trucks
    source:
      location: food.trucks
      columns:
        - name: truck_id
        - name: city
    key: [truck_id]
```

Input SQL:

```sql
SELECT
  DATE_TRUNC('month', sold_at) AS month,
  truck.city,
  AGG(avg_daily_revenue_per_truck),
  AVG(COUNT(*) PER (truck_id)) AS avg_sales_per_truck
FROM sales
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."month" AS "month",
  "grouped"."city" AS "city",
  AVG("grouped"."avg_daily_revenue_per_truck") FILTER(WHERE
    "grouped"."_group_id" = 0) AS "avg_daily_revenue_per_truck",
  AVG("grouped"."avg_sales_per_truck") FILTER(WHERE
    "grouped"."_group_id" = 1) AS "avg_sales_per_truck"
FROM (
  SELECT
    DATE_TRUNC('MONTH', "sales"."sold_at") AS "month",
    "truck"."city" AS "city",
    SUM("sales"."amount") AS "avg_daily_revenue_per_truck",
    COUNT(*) AS "avg_sales_per_truck",
    GROUPING(CAST("sales"."sold_at" AS DATE)) AS "_group_id"
  FROM "food"."truck_sales" AS "sales"
  LEFT JOIN "food"."trucks" AS "truck"
    ON "truck"."truck_id" = "sales"."truck_id"
  GROUP BY
    GROUPING SETS (
      (
        DATE_TRUNC('MONTH', "sales"."sold_at"),
        "truck"."city",
        "sales"."truck_id",
        CAST("sales"."sold_at" AS DATE)
      ),
      (DATE_TRUNC('MONTH', "sales"."sold_at"), "truck"."city", "sales"."truck_id")
    )
) AS "grouped"
GROUP BY
  "grouped"."month",
  "grouped"."city"
```

Sum revenue per truck and day, then average those: the typical truck's daily revenue.

Queries can use `PER` too: here, the average number of sales per truck.

Only days with sales count. To count idle days as 0, use `WITH FILL` with a calendar.

See [Multi-level aggregation](/metricflow/complex-metrics#multi-level-aggregation-per) and [Spines](/metricflow/complex-metrics#spines-with-fill).

### Period over period and year to date

Compare each month's revenue with the same month last year, and keep a running total for the year.
Here, `calendar` has a row per day, with `month` computed from the day, and `year` from the month.

```yaml
datasets:
  - name: calendar
    source:
      location: shop.calendar
      columns:
        - name: day
    key: [day]
    calculations:
      - name: month
        expr: DATE_TRUNC('month', day)
      - name: year
        expr: YEAR(month)
  - name: orders
    source:
      location: shop.orders
      columns:
        - name: order_id
        - name: amount
        - name: sold_at
    key: [order_id]
    relationships:
      - name: sold_on
        target: calendar
        key: [{ name: day, expr: CAST(sold_at AS DATE) }]
        always_matches: true
    calculations:
      - name: revenue
        expr: SUM(amount)
      - name: revenue_last_year
        expr: >-
          SUM(
            LAG(AGG(revenue), 12) OVER (
              PARTITION BY EXCLUDING sold_on.month
              ORDER BY sold_on.month
            )
            PER (sold_on.month WITH FILL)
          )
```

Input SQL:

```sql
SELECT
  sold_on.year,
  sold_on.month,
  AGG(revenue),
  AGG(revenue_last_year),
  AGG(revenue) / AGG(revenue_last_year) - 1 AS yoy_growth,
  SUM(AGG(revenue)) OVER (PARTITION BY sold_on.year ORDER BY sold_on.month) AS revenue_ytd
FROM orders
WHERE sold_on.month >= DATE '2025-01-01'
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "windowed"."year" AS "year",
  "windowed"."month" AS "month",
  "windowed"."revenue" AS "revenue",
  "windowed"."revenue_last_year" AS "revenue_last_year",
  "windowed"."yoy_growth" AS "yoy_growth",
  SUM("windowed"."_agg") OVER (PARTITION BY "windowed"."year" ORDER BY "windowed"."month") AS "revenue_ytd"
FROM (
  SELECT
    "grouped"."year" AS "year",
    "grouped"."month" AS "month",
    MAX("grouped"."revenue") AS "revenue",
    SUM("grouped"."revenue_last_year") AS "revenue_last_year",
    MAX("grouped"."revenue") / SUM("grouped"."revenue_last_year") - 1 AS "yoy_growth",
    MAX("grouped"."revenue") AS "_agg"
  FROM (
    WITH "_unfilled" AS (
      SELECT
        YEAR(DATE_TRUNC('MONTH', "sold_on"."day")) AS "year",
        DATE_TRUNC('MONTH', "sold_on"."day") AS "month",
        SUM("orders"."amount") AS "revenue",
        COUNT(*) AS "_rows"
      FROM "shop"."orders" AS "orders"
      LEFT JOIN "shop"."calendar" AS "sold_on"
        ON "sold_on"."day" = CAST("orders"."sold_at" AS DATE)
      GROUP BY
        YEAR(DATE_TRUNC('MONTH', "sold_on"."day")),
        DATE_TRUNC('MONTH', "sold_on"."day")
    )
    SELECT
      "filled"."year" AS "year",
      "filled"."month" AS "month",
      "filled"."revenue" AS "revenue",
      LAG("filled"."revenue", 12) OVER (ORDER BY "filled"."month") AS "revenue_last_year",
      "filled"."_rows" AS "_rows"
    FROM (
      SELECT
        COALESCE("_unfilled"."year", "keys"."year") AS "year",
        COALESCE("_unfilled"."month", "keys"."month") AS "month",
        "_unfilled"."revenue" AS "revenue",
        "_unfilled"."_rows" AS "_rows"
      FROM (
        SELECT
          YEAR("spine"."_fill_col") AS "year",
          "spine"."_fill_col" AS "month"
        FROM (
          SELECT DISTINCT
            DATE_TRUNC('MONTH', "sold_on"."day") AS "_fill_col"
          FROM "shop"."calendar" AS "sold_on"
        ) AS "spine"
        WHERE
          "spine"."_fill_col" BETWEEN (
            SELECT
              MIN("month")
            FROM "_unfilled"
          ) AND (
            SELECT
              MAX("month")
            FROM "_unfilled"
          )
      ) AS "keys"
      FULL OUTER JOIN "_unfilled"
        ON "_unfilled"."month" = "keys"."month"
        AND "_unfilled"."year" IS NOT DISTINCT FROM "keys"."year"
    ) AS "filled"
  ) AS "grouped"
  GROUP BY
    "grouped"."year",
    "grouped"."month"
  HAVING
    NOT MAX("grouped"."_rows") IS NULL
) AS "windowed"
WHERE
  "windowed"."month" >= CAST('2025-01-01' AS DATE)
```

`LAG(..., 12)` reads the value 12 months back.

`WITH FILL` adds months without orders, so `LAG` always steps back exactly 12 months.

Because `year` is computed from `month`, excluding the month excludes the year too, so `LAG` can reach last year.
With `YEAR(day)`, the window would be split by year.

Calculations combine like any aggregate: here, growth over last year.

A running total, partitioned by year, gives year to date. For month to date, group by day and partition by month.

This filter applies after the window, so January 2025 still reads January 2024.

See [Spines: `WITH FILL`](/metricflow/complex-metrics#spines-with-fill).

### Daily, weekly and monthly active users

Count distinct active users each day, and over the last 7 and 30 days.
Distinct counts don't add up, so summing daily counts over 7 days counts a user once per active day.
Instead, check each user on each day, then count the users.

```yaml
datasets:
  - name: calendar
    source:
      location: shop.calendar
      columns:
        - name: day
    key: [day]
  - name: events
    source:
      location: web.events
      columns:
        - name: event_id
        - name: user_id
        - name: occurred_at
    key: [event_id]
    relationships:
      - name: active_on
        target: calendar
        key: [{ name: day, expr: CAST(occurred_at AS DATE) }]
        always_matches: true
    calculations:
      - name: event_count
        expr: COUNT(*)
      - name: active_users
        expr: COUNT(DISTINCT user_id)
      - name: active_users_7d
        expr: >-
          COUNT(
            MAX(AGG(event_count)) OVER (
              PARTITION BY EXCLUDING active_on.day
              ORDER BY active_on.day
              RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW
            )
            PER (user_id, active_on.day WITH FILL)
          )
      - name: active_users_30d
        expr: >-
          COUNT(
            MAX(AGG(event_count)) OVER (
              PARTITION BY EXCLUDING active_on.day
              ORDER BY active_on.day
              RANGE BETWEEN INTERVAL 29 DAY PRECEDING AND CURRENT ROW
            )
            PER (user_id, active_on.day WITH FILL)
          )
```

Input SQL:

```sql
SELECT
  active_on.day,
  AGG(active_users) AS dau,
  AGG(active_users_7d) AS wau,
  AGG(active_users_30d) AS mau
FROM events
GROUP BY ALL
```

Compiled SQL:

```sql
SELECT
  "grouped"."day" AS "day",
  MAX("grouped"."dau") FILTER(WHERE
    "grouped"."_group_id" = 1) AS "dau",
  COUNT("grouped"."wau") FILTER(WHERE
    "grouped"."_group_id" = 0) AS "wau",
  COUNT("grouped"."mau") FILTER(WHERE
    "grouped"."_group_id" = 0) AS "mau"
FROM (
  WITH "_unfilled" AS (
    SELECT
      CAST("events"."occurred_at" AS DATE) AS "day",
      "events"."user_id" AS "user_id",
      COUNT(DISTINCT "events"."user_id") AS "dau",
      COUNT(*) AS "event_count",
      COUNT(*) AS "_rows",
      GROUPING("events"."user_id") AS "_fill_grouping_0",
      GROUPING(CAST("events"."occurred_at" AS DATE)) * 2 + GROUPING("events"."user_id") AS "_fill_set"
    FROM "web"."events" AS "events"
    GROUP BY
      GROUPING SETS (
        (CAST("events"."occurred_at" AS DATE)),
        (CAST("events"."occurred_at" AS DATE), "events"."user_id")
      )
  )
  SELECT
    "filled"."day" AS "day",
    "filled"."dau" AS "dau",
    MAX("filled"."event_count") OVER (
      PARTITION BY "filled"."user_id", "filled"."_fill_grouping_0"
      ORDER BY "filled"."day"
      RANGE BETWEEN INTERVAL '6' DAY PRECEDING AND CURRENT ROW
    ) AS "wau",
    MAX("filled"."event_count") OVER (
      PARTITION BY "filled"."user_id", "filled"."_fill_grouping_0"
      ORDER BY "filled"."day"
      RANGE BETWEEN INTERVAL '29' DAY PRECEDING AND CURRENT ROW
    ) AS "mau",
    "filled"."_rows" AS "_rows",
    "filled"."_fill_grouping_0" AS "_group_id"
  FROM (
    SELECT
      COALESCE("_unfilled"."day", "keys"."day") AS "day",
      COALESCE("_unfilled"."user_id", "keys"."user_id") AS "user_id",
      COALESCE("_unfilled"."_fill_grouping_0", "keys"."_fill_grouping_0") AS "_fill_grouping_0",
      "_unfilled"."dau" AS "dau",
      "_unfilled"."event_count" AS "event_count",
      "_unfilled"."_rows" AS "_rows"
    FROM (
      SELECT
        "spine"."_fill_col" AS "day",
        (
          SELECT
            "user_id"
          FROM "_unfilled"
          WHERE
            FALSE
        ) AS "user_id",
        1 AS "_fill_grouping_0",
        1 AS "_fill_set"
      FROM (
        SELECT DISTINCT
          "active_on"."day" AS "_fill_col"
        FROM "shop"."calendar" AS "active_on"
      ) AS "spine"
      WHERE
        "spine"."_fill_col" BETWEEN (
          SELECT
            MIN("day")
          FROM "_unfilled"
        ) AND (
          SELECT
            MAX("day")
          FROM "_unfilled"
        )
      UNION ALL
      SELECT
        "spine"."_fill_col" AS "day",
        "parts"."user_id",
        0 AS "_fill_grouping_0",
        0 AS "_fill_set"
      FROM (
        SELECT DISTINCT
          "active_on"."day" AS "_fill_col"
        FROM "shop"."calendar" AS "active_on"
      ) AS "spine"
      CROSS JOIN (
        SELECT DISTINCT
          "user_id"
        FROM "_unfilled"
        WHERE
          NOT "day" IS NULL AND "_fill_set" = 0
      ) AS "parts"
      WHERE
        "spine"."_fill_col" BETWEEN (
          SELECT
            MIN("day")
          FROM "_unfilled"
        ) AND (
          SELECT
            MAX("day")
          FROM "_unfilled"
        )
    ) AS "keys"
    FULL OUTER JOIN "_unfilled"
      ON "_unfilled"."day" = "keys"."day"
      AND "_unfilled"."user_id" IS NOT DISTINCT FROM "keys"."user_id"
      AND "_unfilled"."_fill_set" = "keys"."_fill_set"
  ) AS "filled"
) AS "grouped"
GROUP BY
  "grouped"."day"
HAVING
  NOT MAX("grouped"."_rows") FILTER(WHERE
    "grouped"."_group_id" = 0) IS NULL
```

One row per user and day, including days the user wasn't active.

For each user and day, this is NULL unless the user had an event in the last 7 days.

`COUNT` counts the users that aren't NULL: each active user once.

This makes a row per user per day, so it's costly over many users and a long history. Filtering by day doesn't make it smaller.

See [`OVER`, `PER`, and `WITH FILL` together](/metricflow/complex-metrics#over-per-and-with-fill-together).

# dbt

MetricFlow works with dbt v1, as the `dbt-metricflow-sql` plugin, and with dbt v2, built in behind the
`metricflow_v2` flag (see [Quickstart](/metricflow/quickstart)). Both read the same YAML and vars, below.

## Semantics

Datasets, entities, constellations, pages and policies can be added under the `semantics` key
of any dbt schema file:

```yaml
version: 2

sources: [...]
models: [...]
semantics:
  datasets: [...]
  entities: [...]
  constellations: [...]
  pages: [...]
  policies: [...]
```

Files that define the same object are merged.

Datasets are built on top of dbt models or sources, and can reference them with `ref(...)` or `source(...)`:

```yaml
semantics:
  datasets:
    - name: orders
      source: ref('orders')
      calculations:
        - name: revenue
          expr: SUM(gross - discount)
```

## Inline datasets

Within dbt, models and sources become datasets if they include any calculations, relationships or
permissions:

```yaml
models:
  - name: orders
    columns:
      - name: gross
      - name: discount
    calculations:
      - name: revenue
        expr: SUM(gross - discount)
```

Or, to turn any model into a dataset with only columns:

```yaml
models:
  - name: orders
    columns:
      - name: gross
      - name: discount
    dataset: true
```

## Macros

Like the rest of a schema file, semantics, dataset fields and pages are rendered with Jinja, and can
call the project's macros:

```sql title="macros/order_size.sql"
{% macro order_size(amount) %}
  CASE WHEN {{ amount }} >= 1000 THEN 'large' WHEN {{ amount }} >= 100 THEN 'medium' ELSE 'small' END
{% endmacro %}
```

```yaml
models:
  - name: orders
    calculations:
      - name: size
        expr: "{{ order_size('gross') }}"
```

Macros can't query the warehouse, e.g. with `run_query`. The SQL of `sql` sources isn't rendered,
since its `{{ }}` are the dataset's parameters, filled in as it's queried.

## MetricFlow SQL models

A model configured with `metricflow=true` is written in MetricFlow SQL:

```sql title="models/revenue_by_plan.sql"
{{ config(materialized='table', metricflow=true) }}

SELECT
  month,
  customer.plan,
  AGG(revenue) AS revenue
FROM orders
GROUP BY ALL
```

These are compiled to warehouse SQL whenever dbt compiles them, e.g. in `dbt compile`, `dbt run`, or `dbt build`, and behave like any other model, with Jinja rendering, upstream dependencies, selectors, tests, etc.

**dbt v1**

Compiling these models needs the `sidecar` extra (see [Quickstart](/metricflow/quickstart)).

**dbt v2**

dbt downloads MetricFlow's sidecar the first time it compiles one of these models.

## Settings

MetricFlow supports these optional dbt vars. Set them in `dbt_project.yml`:

```yaml
vars:
  metricflow_convert_legacy: true
```

Or for one command:

```sh
dbt build --vars '{metricflow_publish_env: prod}'
```

| Var | Default | Description |
| --- | --- | --- |
| `metricflow_convert_legacy` | `false` | Converts your legacy MetricFlow semantic models and metrics to MetricFlow v2. Anything it can't convert shows up as a warning. |
| `metricflow_publish` | Automatic | Whether `dbt run` and `dbt build` publish your semantic layer. By default, they publish when your project is connected to the dbt platform. |
| `metricflow_publish_env` | The target's schema | The environment to publish to, e.g. `prod`. You query it by this name. |
| `metricflow_publish_profile` | The environment's profile | The dbt platform profile, a warehouse connection, to run queries with. Only needed to create a new environment. See [dbt platform setup](/metricflow/dbt-platform-setup). |
| `metricflow_publish_url` | Your dbt platform account | The MetricFlow server to publish to, if it isn't your dbt platform account's. |
| `metricflow_server` | The sidecar | The command that runs MetricFlow locally, instead of the sidecar: dbt v1's `sidecar` extra, or the one dbt v2 downloads. |

In dbt v2, `metricflow_convert_legacy` converts the semantic models and metrics that dbt v2 reads, which
are configured on your models' entries. A project still on the legacy top-level `semantic_models:` YAML
has none for dbt v2 to convert.

# SQL

MetricFlow's server speaks the [Trino](https://trino.io/docs/current/develop/client-protocol.html) client protocol, so any Trino client can query it.
See Trino's [client list](https://trino.io/docs/current/client.html).

Queries are MetricFlow SQL, compiled to your warehouse's SQL and run there.
`EXPLAIN <query>` returns the compiled SQL without running it.

## Connecting

| Setting | Value |
|---|---|
| Host | Your account's Semantic Layer host, e.g. `ab123.semantic-layer.us1.dbt.com` |
| Authentication | A dbt platform token, as a bearer token (Trino calls it an access token, or JWT), or as a password, with any user |
| Catalog | The environment to query, e.g. `prod`. Without one, the server's default |

Queries are read as Trino's SQL dialect.
To write them in your warehouse's dialect instead, send its name in the `X-Dbt-Dialect` header, e.g. `bigquery`.

## Examples

With the [Trino CLI](https://trino.io/docs/current/client/cli.html):

```sh
trino --server https://ab123.semantic-layer.us1.dbt.com \
  --access-token "$DBT_CLOUD_TOKEN" \
  --catalog prod \
  --execute "SELECT customer.plan, AGG(revenue) FROM orders GROUP BY ALL"
```

With Python's [`trino`](https://github.com/trinodb/trino-python-client) package:

```python
import os

import trino

connection = trino.dbapi.connect(
    host="ab123.semantic-layer.us1.dbt.com",
    port=443,
    http_scheme="https",
    auth=trino.auth.JWTAuthentication(os.environ["DBT_CLOUD_TOKEN"]),
    catalog="prod",
)
cursor = connection.cursor()
cursor.execute("SELECT customer.plan, AGG(revenue) FROM orders GROUP BY ALL")
print(cursor.fetchall())
```

From a dbt project, the `query` command does the same with the project's settings:

**dbt v1**

```sh
dbtsl query "SELECT customer.plan, AGG(revenue) FROM orders GROUP BY ALL"
```

**dbt v2**

```sh
dbt sl2 query "SELECT customer.plan, AGG(revenue) FROM orders GROUP BY ALL"
```

# API

Besides [SQL](/metricflow/integrations/sql), MetricFlow's server has a JSON API, on the same host, for reading the semantic layer's objects.

Requests authenticate with a dbt platform token, as `Authorization: Bearer <token>`, and name the environment to read in the `X-Trino-Catalog` header, e.g. `prod`. Without it, they read the account's default environment.

## Endpoints

| Endpoint | Does |
|---|---|
| `POST /v1/statement` | Runs a query, over Trino's protocol (see [SQL](/metricflow/integrations/sql)) |
| `GET /v1/search?q=<terms>&limit=<n>&offset=<n>&type=<type>` | Searches objects and pages, for up to 100 results, 10 by default, after skipping `offset`. Repeat `type` to keep only those types, e.g. `type=Metric&type=Calculation` |
| `GET /v1/objects?id=<id>&id=...` | Gets up to 100 objects by id, each `null` if there's none |
| `POST /v1/graphql` | Reads objects and the links between them as a graph, in one request (see [GraphQL](#graphql)) |

Ids are references, e.g. `metric:finance:margin` or `p:glossary` (see [Pages](/metricflow/pages)).

## Examples

```sh
curl "https://ab123.semantic-layer.us1.dbt.com/v1/search?q=margin" \
  -H "Authorization: Bearer $DBT_CLOUD_TOKEN" \
  -H "X-Trino-Catalog: prod"
```

```json
{
  "results": [
    {
      "id": "f:finance:pnl:margin",
      "type": "Metric",
      "label": "Margin",
      "description": "...",
      "parent": "t:finance:pnl",
      "score": 1.0
    },
    {
      "id": "p:glossary",
      "type": "Page",
      "label": "Glossary",
      "description": null,
      "parent": null,
      "section": ["Margin"],
      "text": "...",
      "score": 0.8
    }
  ],
  "total": 12,
  "next_offset": 2
}
```

Each result names its object's `type` (Table, View, Column, Calculation, Relationship, Entity,
Source, Attribute, Constellation, Role, Metric, Fact, Assignment or Page) and its `parent`, the dataset,
constellation or entity it lives on, if any. Only a page's results carry `text`, the passage that
matched, and `section`, its heading trail when it's under a heading. `total` counts the matches
across every page, and `next_offset` is the `offset` for the next page, `null` on the last.

```sh
curl "https://ab123.semantic-layer.us1.dbt.com/v1/objects?id=metric:finance:margin&id=p:glossary" \
  -H "Authorization: Bearer $DBT_CLOUD_TOKEN" \
  -H "X-Trino-Catalog: prod"
```

```json
{"objects": {"metric:finance:margin": {...}, "p:glossary": {...}}}
```

## GraphQL

`POST /v1/graphql` lets one request fetch an object and the objects it references, e.g. a constellation, its metrics, and the datasets they read. Every query and type is in the [GraphQL schema reference](/metricflow/reference/graphql/schema). You can also open `/v1/graphql` in a browser for GraphiQL, to try queries.

```sh
curl "https://ab123.semantic-layer.us1.dbt.com/v1/graphql" \
  -H "Authorization: Bearer $DBT_CLOUD_TOKEN" \
  -H "X-Trino-Catalog: prod" \
  -H "Content-Type: application/json" \
  -d '{"query": "{ node(id: \"constellation:finance\") { ... on Constellation { resolvedMetrics { nodes { name facts { dataset { name } } } } } } }"}'
```

# MCP

AI agents can use MetricFlow through [dbt's remote MCP server](https://docs.getdbt.com/docs/dbt-ai/about-mcp), which gives them tools to search the semantic layer, read its objects and pages, and run queries.

MetricFlow's tools in dbt's remote MCP server aren't enabled by default. Reach out to us to get them enabled for your account.

Add `?sl_version=2` or `?sl_version=1` to the server URL to choose MetricFlow v2's tools or v1's. See
[Running alongside v1](/metricflow/deploying-alongside-v1#mcp).

# Schema

> Every field of a fragment file, and of the types it holds.

## Fragment

A piece of a bundle's semantic graph: the fragments of a bundle are merged into it.

Datasets, entities and constellations are named like a warehouse's tables: `sales.orders` is
`orders` in the `sales` namespace, and a name without a namespace is in `public`. A reference
without a namespace, e.g. a relationship's `entity: customer`, is in the namespace of the
object that declares it. A dataset and a constellation can't share a name.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `bundle` | string | **required** | The name of the bundle this fragment is part of, e.g. a dbt project's name. Every fragment in a bundle has the same one: it identifies the bundle when it's published. It's a segment of the bundle's URL, so it can't contain a `/`. Has at least 1 character(s). Matches `^[^/]+$`. |
| `dialect` | string | **required** | The default SQL dialect used to parse expressions and datatypes. |
| `schema_version` | `"v1"` | **required** |  |
| `constellations` | list of [Constellation](#constellation) | `[]` | Constellations. |
| `datasets` | list of [Dataset](#dataset) | `[]` | Datasets. |
| `entities` | list of [Entity](#entity) | `[]` | Entities. |
| `generation_meta` | [FragmentMetadata](#fragmentmetadata) | optional | Header describing the production of this fragment. |
| `pages` | list of [Page](#page) | `[]` | Wiki pages. |
| `policies` | list of [Policy](#policy) | `[]` | Permissions reused by name, by any fragment of the bundle. |


### FragmentMetadata

Header describing the production of this fragment.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `env` | string or null | `null` | Environment |
| `generated_at` | string or null | `null` | When the fragment was generated. |
| `generator_name` | string or null | `null` | The name of the tool that generated this fragment. |
| `generator_version` | string or null | `null` | The version of the tool that generated this fragment. |
| `invocation_id` | string or null | `null` | The invocation that generated this fragment, if applicable. |


## Constellation

A group of fact tables connected by conformed dimensions.

Constellations capture higher-order business domains and enable
multi-fact queries. Constellations can include configuration from other
constellations.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `description` | string or null | `null` |  |
| `facts` | list of [Fact](#fact) | `[]` | The datasets of the constellation, and the roles they provide. |
| `imports` | list of [Import](#import) | `[]` | Other constellations to import fields from. |
| `label` | string or null | `null` |  |
| `metrics` | list of [Metric](#metric) | `[]` | Metrics of the constellation. |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |
| `roles` | list of [Role](#role) | `[]` | Roles of the constellation. |


### Fact

A dataset of the constellation, and the roles it provides.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `dataset` | string | **required** | The name of the dataset. |
| `alias` | string or null | `null` | The name metrics read the dataset by, e.g. `AGG(visits.count)`, unique among the constellation's facts. Defaults to the dataset's name. |
| `roles` | list of (string or [Assignment](#assignment)) | `[]` | How the dataset provides each role. A name, e.g. `status`, assigns the dataset's field of that name to the role of that name, which the constellation declares if no fragment does. |


### Assignment

Defines how a dataset provides a role.

This is akin to "dimension conforming" in traditional dimensional
modeling, allowing cross-table analysis - queries reference roles, and the
physical location of roles are resolved per dataset.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `expr` | string | **required** | A SQL expression, where columns resolve relative to the dataset. |
| `name` | string | **required** | The name of the role, unique among the fact's roles. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |


### Import

Specification for how one constellation imports another.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `constellation` | string | **required** | The name of the constellation to import from. |
| `fields` | string or list of string | **required** | Which fields to import: `*`, a field name, `!name` to exclude a field, or a list of these, e.g. `['*', '!refunds']`. Has at least 1 item(s). |


### Metric

An aggregatable measurement.

Metrics are typically quantitative, but they can be any aggregatable
value. Metrics can span multiple datasets.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `expr` | string | **required** | A SQL expression, where qualified columns reference fields of the constellation's facts, by alias, e.g. `orders.revenue`, and unqualified columns reference other metrics or roles. |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | Optionally define the datatype. If left null, this will be inferred. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


### Permission

Who can use an object or field, and for them, what's filtered or masked.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `groups` | list of string | **required** | dbt platform groups that can use it, or `*` for everyone. Has at least 1 item(s). |
| `having` | string or null | `null` | A SQL condition over aggregates that the groups' aggregated results must pass. Only for datasets, entities and constellations. |
| `mask` | string or null | `null` | A SQL expression the groups see instead of a field's value, reading the field for its own value. Not for relationships. |
| `where` | string or null | `null` | A SQL condition the rows the groups see must pass. Only for datasets, entities and constellations. |


### Role

A qualitative property that describes metrics - metrics can be sliced
and diced by roles.

Each dataset contributing to a constellation can assign fields to a role.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | A physical data type, or `REF(<name>)` for a reference to an entity or dataset, in which case datasets must implement the role with a relationship. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


## Dataset

Physical dataset - serves as the input to the semantic layer graph

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `calculations` | list of [Calculation](#calculation) | `[]` | Derived columns. |
| `description` | string or null | `null` |  |
| `key` | list of (string or [KeyCondition](#keycondition)) | `[]` | What identifies a row: names of fields, whose values identify rows, and conditions, e.g. `[user_id, {on: ':as_of >= valid_from AND :as_of < valid_to'}]`. Relationships binding all of it are many-to-one. Requires `source`. |
| `label` | string or null | `null` |  |
| `parameters` | list of [Parameter](#parameter) | `[]` | Values a query passes, read by calculations as `:name` and by a `sql` source's template. |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |
| `relationships` | list of [Relationship](#relationship) | `[]` | References to entities and datasets. |
| `source` | [DatasetSource](#datasetsource) or null | `null` | Source of this dataset (a physical table or a query). Omit it to add calculations and relationships to a dataset whose source another fragment of the bundle defines. |


### Calculation

A derived column on the dataset.

`expr` is a SQL expression, where columns reference other columns,
calculations, or relationships.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `expr` | string | **required** | A SQL expression, relative to the dataset. |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | Optionally define the datatype. If left null, this will be inferred. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


### KeyCondition

A key part that identifies rows by a condition rather than a field's value.

For example, `:as_of >= valid_from AND :as_of < valid_to` for versions valid
over a period.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `on` | string | **required** | A SQL condition, where columns are relative to the dataset and values a relationship binds are `:`-prefixed placeholders, which can't be named like the dataset's fields or parameters. |
| `params` | list of [KeyParameter](#keyparameter) or null | `null` | The condition's placeholders. If left null, they are inferred from `on`, and they must be exactly its placeholders otherwise. |


### KeyParameter

A placeholder of a key condition, e.g. `:as_of`.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | The parameter's data type. |


### Parameter

A value a query passes on its root table function, e.g. `ds(min_quantity => 90)`.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | The parameter's data type. |
| `default` | string or null | `null` | A constant used when a query passes nothing; NULL when absent. |


### Relationship

A relationship to an entity or a dataset, its target.

A key binding all of the target's key is many-to-one, and any other is
one-to-many.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `target` | string | **required** | The name of the related entity or dataset. An entity is looked up first, then a dataset. |
| `always_matches` | boolean | `false` | Whether every non-NULL key has a matching row in the target, like a foreign key. Then reading the target's key fields needs no join. Many-to-one only. |
| `cardinality` | `"many_to_one"` or `"one_to_many"` or null | `null` | Optionally declare the cardinality. If left null, this will be inferred from the key, and it must agree with it otherwise. |
| `description` | string or null | `null` |  |
| `key` | list of [RelationshipKeyColumn](#relationshipkeycolumn) | `[]` | Expressions on this dataset for the target's fields. |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


### RelationshipKeyColumn

How a relationship binds one of its target's fields.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `expr` | string | **required** | A SQL expression, relative to the dataset. `:name` passes on a key the dataset itself was joined by, e.g. `:as_of`. |
| `name` | string | **required** | A key column of the target entity, or a key part or field of the target dataset, unique among the key's. |


### DatasetSource

A physical table, or a query.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `columns` | list of [Column](#column) | `[]` | Columns of the table or query's rows. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `location` | string or null | `null` | The fully-qualified physical table this dataset reads from. |
| `sql` | string or null | `null` | A query whose rows this dataset reads, e.g. a filtered table. A Jinja template over the dataset's parameters. |
| `type` | `"sql"` or `"table"` | `"table"` | `table` reads `location`; `sql` reads the rows `sql` returns. |


### Column

A concrete column in the underlying database.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | The column's data type. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


## Entity

An identifiable, referencable business object.

Entities are like virtual datasets, composed from many datasets.
Attributes act like an entity's columns.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `attributes` | list of (string or [Attribute](#attribute)) | `[]` | Properties of the entity. With one source, a string reads fields of its dataset, each as `<dataset>.<field>`: `*` for each of its columns and calculations, a field's name, or `!name` to leave a field out of `*`, e.g. `['*', '!ssn']`. An entity with permissions of its own can't have `*`. |
| `description` | string or null | `null` |  |
| `key` | list of [EntityKeyColumn](#entitykeycolumn) | `[]` | The interface that sources must implement and dataset relationships reference. |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |
| `sources` | list of [Source](#source) | `[]` | Datasets implementing the entity's key. |


### Attribute

A property of an entity.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `expr` | string | **required** | SQL expression, where qualified columns reference fields from a source and unqualified columns reference other attributes. |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | Optionally define the datatype. If left null, this will be inferred. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `permissions` | list of [Permission](#permission) or null | `null` | Who can use it, checked in order: the first that lists any of a caller's groups applies. If left null, whoever can use what it reads can use it. Has at least 1 item(s). |
| `policy` | string or null | `null` | The name of a policy whose permissions it has, instead of its own. |


### EntityKeyColumn

Specification for an individual entity key column.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique among its collection's. |
| `datatype` | string or null | `null` | The key column's data type. |
| `optional` | boolean | `false` | Whether dataset relationships may omit referencing this key column. |


### Source

A dataset sourcing the entity.

Entities have attributes that are sourced from many datasets - a source
defines such a dataset.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `dataset` | string | **required** | The name of the dataset, unique among the entity's sources. |
| `on` | string | **required** | A SQL expression that defines how the dataset implements the entity's key. Used as the ON clause of JOIN expressions: columns are relative to the dataset, and entity key values from the other side of the join are referencable with `:`-prefixed variables. |


## Page

A markdown wiki page, or with a glob `path`, one for each markdown file it matches.

    Links to other objects are markdown links with a reference as the URL, e.g.
    `[revenue](metric:sales:revenue)` or `[onboarding](page:guides/onboarding)`. A relative link
    to another page's markdown file, e.g. `[onboarding](guides/onboarding.md)`, becomes a
    reference to that page.

    A markdown file may start with YAML frontmatter setting the page's `name`, `label`,
    `description` and `meta`, e.g. `---
label: Onboarding
---`.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `content` | string or null | `null` | The page's markdown, inline. Exclusive with `path`. |
| `description` | string or null | `null` |  |
| `label` | string or null | `null` |  |
| `name` | string or null | `null` | The name, unique among its collection's. Required with `content`. With a file `path`, it defaults to its frontmatter's, else the file's name without `.md`, e.g. `onboarding` for `wiki/onboarding.md`. |
| `path` | string or null | `null` | Path to a markdown file holding the page's content, relative to this fragment file within its bundle. Or a glob, as dbt's `path:` selector: a page for each `.md` file it matches, or that's under a directory it matches, e.g. `wiki` or `wiki/**/*.md`. Each is named by its path within the glob's directory, its leading names without wildcards, without `.md`, e.g. `guides/onboarding` for `wiki/guides/onboarding.md`, unless its frontmatter names it; then the page sets no `name`, `label` or `description`. Exclusive with `content`. |


## Policy

Permissions that objects and fields reuse by name.

| Field | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | string | **required** | The name, unique within the bundle. |
| `permissions` | list of [Permission](#permission) | **required** | The permissions. Has at least 1 item(s). |


## Fields of every type

Besides the fields in its table, every type in this reference accepts:

- `meta`: object, defaulting to `{}`.

# Extensions

MetricFlow SQL is standard SQL, plus the extensions on this page.

In the syntax blocks, `<name>` is a placeholder, `[ ... ]` is optional, `{ a | b }` is a choice, and
`[ , ... ]` means the item before it can repeat.

## Predefined aggregations

`AGG` runs an aggregation defined in a dataset or constellation: an aggregate calculation or a metric.
It's grouped by the query's `GROUP BY`, or over all rows without one.

```text
AGG( <calculation_or_metric> ) [ FILTER ( WHERE <condition> ) ]
```

- `<calculation_or_metric>`: the name of an aggregate calculation of a dataset, or a metric of a
  constellation.
- `FILTER ( WHERE <condition> )`: aggregates only the rows that match `<condition>`.

For example:

```sql
SELECT
  region,
  AGG(revenue),
  AGG(revenue) FILTER (WHERE status = 'returned') AS returned_revenue
FROM orders
GROUP BY region
```

- `AGG` can go anywhere an aggregate can: `SELECT`, `HAVING`, `ORDER BY`, and inside window functions.
- Aggregate calculations and metrics can only be queried with `AGG`.
- See [Datasets](/metricflow/datasets#calculations) and [Constellations](/metricflow/constellations#metrics)
  for more examples.

## Multi-level aggregation

`PER` aggregates in two steps. First the inner aggregate, grouped by the query's `GROUP BY` plus the
`PER` columns. Then the outer aggregate, over those results, grouped by the query's `GROUP BY`.

```text
<outer_aggregate>( <inner_aggregate> PER ( <per_expr> [ WITH FILL [ FROM ( <query> ) ] ] [ , ... ] ) )
```

- `<inner_aggregate>`: any aggregate, or expression of them, e.g. `SUM(amount)`, `AGG(revenue)` or
  `AGG(revenue) - AGG(cost)`. `PER` applies to all of it. It can contain another `PER`, or a window
  function, which runs at the `PER`'s grain.
- `<per_expr>`: a column or expression to also group the inner aggregate by.
- `<outer_aggregate>`: any aggregate function, e.g. `AVG`, `MAX` or `COUNT`, without `OVER`. It can
  only read the `PER` columns, not other columns.
- `WITH FILL`: see [Filling missing values](#filling-missing-values).

For example, this sums each customer's orders, then averages those sums in each region:

```sql
SELECT
  region,
  AVG(SUM(amount) PER (customer_id)) AS avg_spend_per_customer
FROM orders
GROUP BY region
```

- `PER` works on any table, not only datasets, and in calculations and metrics.
- See [Complex metrics](/metricflow/complex-metrics#multi-level-aggregation-per) for more examples.

## Window functions

Window functions work as in standard SQL, with two extensions: they can run over `AGG`, and
`PARTITION BY` takes an optional `EXCLUDING` keyword.

```text
<window_function> OVER (
  [ PARTITION BY [ EXCLUDING ] <expr> [ , ... ] ]
  [ ORDER BY <expr> [ { ASC | DESC } ] [ , ... ] ]
  [ <frame> ]
)
```

- `<window_function>`: any window function. Its arguments can use `AGG`, e.g. `SUM(AGG(revenue))` or
  `LAG(AGG(revenue))`.
- `EXCLUDING`: partitions by every column in the query's `GROUP BY`, except the `<expr>` columns.
  So one window, e.g. in a calculation, works at any grain. An `<expr>` column the query doesn't
  group by is ignored, unless the window orders by it.
- `ORDER BY` and `<frame>`: as in standard SQL, e.g.
  `ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`. To read every period, e.g. so `LAG` reads
  the day before even when it has no rows, run the window inside a `PER` that fills them, see
  [Filling missing values](#filling-missing-values).

For example, this is a running total in each region, because the window is partitioned by `region`:

```sql
SELECT
  region,
  day,
  SUM(AGG(revenue)) OVER (PARTITION BY EXCLUDING day ORDER BY day) AS running_revenue
FROM orders
GROUP BY region, day
```

- See [Complex metrics](/metricflow/complex-metrics#window-functions-over) for more examples.

## Filling missing values

`WITH FILL` adds rows for values that have none, e.g. days without orders. It goes on a `PER` key,
or on a query's `ORDER BY` key.

```text
<outer_aggregate>( <inner_aggregate> PER ( <per_expr> WITH FILL [ FROM ( <query> ) ] [ , ... ] ) )

SELECT ... GROUP BY ... ORDER BY <expr> WITH FILL [ FROM ( <query> ) ] [ , ... ]
```

- `<per_expr>` or `<expr>`: the key to fill. Without `FROM`, it must be a field read through a
  relationship, e.g. `ordered_on.day`, and its values are that field's values in the related
  dataset, e.g. every day of a calendar.
- `FROM ( <query> )`: takes the values from a query of one column instead. Then the key can be
  any column or expression.
- Values are filled between the first and last ones with rows.
- A `PER` fills each combination of its other keys and the query's `GROUP BY`. An `ORDER BY`
  fills each combination of the keys before the filled one.
- Several keys can be filled. Rows are added for each combination of their values.
- A `PER`'s fill changes its values, not the query's rows: a group with only filled rows isn't
  added. To add rows, fill the query's `ORDER BY`.
- Filled rows have NULL values. Their other columns are NULL too, unless they're computed from
  the key, e.g. `DATE_TRUNC('month', ordered_on.day)`, or a calendar's `year` calculation
  written as `YEAR(month)` when the key is `month`.

For example, this is each region's revenue on the last day, 0 for a region without orders that
day:

```sql
SELECT
  region,
  MAX_BY(COALESCE(AGG(revenue), 0) PER (ordered_on.day WITH FILL), ordered_on.day) AS last_day_revenue
FROM orders
GROUP BY region
```

And this lists every weekday's revenue, NULL for a weekday without orders:

```sql
SELECT
  ordered_on.day,
  AGG(revenue)
FROM orders
GROUP BY 1
ORDER BY ordered_on.day WITH FILL FROM (SELECT day FROM calendar WHERE is_weekday)
```

- `COALESCE` gives filled rows a value. Some warehouses' `MAX_BY` skips NULL values.
- An `ORDER BY` key must be in the `GROUP BY`. `WITH FILL` takes no `TO` or `STEP`.
- See [Complex metrics](/metricflow/complex-metrics#spines-with-fill) for more examples.

## Reference data types

`REF` is a data type whose value is a row of a dataset or entity. Relationships and roles use it.

```text
REF( <dataset_or_entity> )
```

- `<dataset_or_entity>`: the name of the dataset or entity the value points to.

For example:

```yaml
roles:
  - name: customer
    datatype: REF(customer)
```

- A field with a `REF` type can be followed with [relationship traversal](#relationship-traversal).
- See [Constellations](/metricflow/constellations#roles) for more examples.

## Relationship traversal

A dot after a relationship reads a field of the row it points to. MetricFlow adds the join.

Relationships are defined on datasets, but you can follow them from datasets, entities, and
constellations.

```text
<relationship> [ . <relationship> ... ] . <field>
```

- `<relationship>`: a relationship of the dataset, entity, or constellation you're querying, or of
  the one the previous relationship points to. Chain as many as you need.
- `<field>`: a column or calculation of the last dataset or entity.

For example:

```sql
SELECT
  order_id,
  customer.region,
  customer.plan.price
FROM orders
```

- Through a one-to-many relationship, a field can only be read inside `AGG`, e.g.
  `AGG(orders.revenue)` from `customers`. MetricFlow prevents double counting.
- See [Datasets](/metricflow/datasets#relationships) for more examples.

# GraphQL schema

> Every query and type of the GraphQL API.

The schema of [the GraphQL API](/metricflow/integrations/api#graphql), `POST /v1/graphql`.

```graphql
# The GraphQL API's schema, abridged: a type lists only the fields it adds to the interfaces it
# implements, e.g. every `Node` has `id` and `links`, and a description appears only the first
# time. Start from `Query`.

"""The entry points. A query can nest at most 10 levels deep, and use at most 30 aliases."""
type Query {
  """The object an id names, or null."""
  node(id: ID!): Node
  """Objects by id, in order; null for none. At most 100."""
  nodes(ids: [ID!]!): [Node]!
  """Chunks of objects matching `q`, best first, a page at a time."""
  search(q: String!, """At most 100.""" first: Int! = 10, """A page's `endCursor`, for the page after it.""" after: String, """Only objects of these types, e.g. `Page`.""" types: [String!]): SearchHitPage!
}

"""An object in the registry: a dataset, entity or constellation, one of their fields, sources, facts or assignments, or a wiki page."""
interface Node {
  """The object's id. Ids passed in name a kind, then names: `dataset:orders`, `entity:customer`, `constellation:sales`, `metric:sales:revenue` (or `role`, `column`, `calculation`, `relationship`, `attribute`), `fact:sales:orders`, `source:customer:orders`, `assignment:sales:region:orders`, `page:glossary`. A table without a namespace is in `public`. Ids returned are in full, e.g. `f:public:sales:revenue`, and work as input too."""
  id: ID!
  label: String
  description: String
  meta: JSON
  """Whether the caller has access to this object"""
  accessible: Boolean!
  """Links from this object, in order of appearance."""
  links(labels: [String!], """Only links to objects of these types, e.g. `Fact`.""" types: [String!]): [Edge!]!
  """Links to this object, by the id of the object they're from."""
  backlinks(labels: [String!], """Only links from objects of these types, e.g. `Page`.""" types: [String!]): [Edge!]!
}

"""How a fact provides a role."""
type Assignment implements Node {
  """The constellation that defines it."""
  constellation: Constellation
  """The name of the role."""
  name: String!
  """A SQL expression on the fact's dataset."""
  expr: String!
  role: Role
  fact: Fact
}

"""A page of a list. An object's own fields are sorted by name; objects referring to it, e.g. `referencedBy`, by id."""
type AssignmentPage {
  nodes: [Assignment!]!
  """Pass as `after` for the next page; null on the last, which can be empty."""
  endCursor: String
}

"""A property of an entity."""
type Attribute implements Node {
  name: String!
  expr: String!
  datatype: String
  entity: Entity
}

type AttributePage {
  nodes: [Attribute!]!
  endCursor: String
}

"""A derived column of a dataset."""
type Calculation implements Node {
  name: String!
  expr: String!
  datatype: String
  dataset: Dataset
}

type CalculationPage {
  nodes: [Calculation!]!
  endCursor: String
}

enum Cardinality { MANY_TO_ONE ONE_TO_MANY }

"""A concrete column of a dataset's table or query."""
type Column implements Node {
  name: String!
  datatype: String
  dataset: Dataset
}

type ColumnPage {
  nodes: [Column!]!
  endCursor: String
}

"""A group of facts connected by conformed roles. `roles`, `metrics` and `facts` are its own; the `resolved` ones add what it imports, as queries see them: its own fields win over imported ones, and later imports over earlier ones. An import brings the facts providing the roles it includes, and the facts its included metrics read. A role, metric, fact or assignment reached through a constellation is read as part of it, e.g. an imported metric's `facts` are the constellation's."""
type Constellation implements Node {
  name: String!
  namespace: String!
  imports: [Import!]!
  """The roles it defines, by name."""
  roles("""At most 1000.""" first: Int! = 100, after: String): RolePage!
  """Its roles, own and imported, as queries see them, by name."""
  resolvedRoles(first: Int! = 100, after: String): RolePage!
  """The metrics it defines, by name."""
  metrics(first: Int! = 100, after: String): MetricPage!
  """Its metrics, own and imported, as queries see them, by name."""
  resolvedMetrics(first: Int! = 100, after: String): MetricPage!
  """The facts it defines, by name."""
  facts(first: Int! = 100, after: String): FactPage!
  """Its facts, own and imported, as queries see them, by name."""
  resolvedFacts(first: Int! = 100, after: String): FactPage!
}

"""A physical dataset: a table or a query, and its fields."""
type Dataset implements Node {
  name: String!
  namespace: String!
  source: DatasetSource!
  parameters: [Parameter!]!
  """What identifies a row: fields and conditions."""
  key: [KeyPart!]!
  """By name."""
  calculations(first: Int! = 100, after: String): CalculationPage!
  relationships(first: Int! = 100, after: String): RelationshipPage!
  """Facts of constellations that read this dataset, by id."""
  facts(first: Int! = 100, after: String): FactPage!
  """How this dataset sources entities, by id."""
  entitySources(first: Int! = 100, after: String): SourcePage!
  """Relationships that target this dataset, by id."""
  referencedBy(first: Int! = 100, after: String): RelationshipPage!
}

"""What a dataset reads: a physical table, or a query."""
type DatasetSource {
  type: SourceType!
  location: String
  sql: String
  """The dialect `sql` is written in."""
  dialect: String
  """Columns of the table or query's rows, by name."""
  columns(first: Int! = 100, after: String): ColumnPage!
}

"""A link between two objects, from one end's point of view."""
type Edge {
  """What the link is: `parent`, `dependency`, `type`, or a wiki link's text."""
  label: String!
  """The id of the object at the other end."""
  id: ID!
  """The object at the other end; null if it isn't defined."""
  node: Node
}

"""An identifiable, referenceable business object."""
type Entity implements Node {
  name: String!
  namespace: String!
  key: [EntityKeyColumn!]!
  attributes(first: Int! = 100, after: String): AttributePage!
  """The datasets sourcing this entity, by id."""
  sources(first: Int! = 100, after: String): SourcePage!
  """Relationships that target this entity, by id."""
  referencedBy(first: Int! = 100, after: String): RelationshipPage!
  """Roles whose datatype references this entity, by id."""
  roles(first: Int! = 100, after: String): RolePage!
}

"""A column of an entity's key."""
type EntityKeyColumn {
  name: String!
  datatype: String
  optional: Boolean!
}

"""A dataset of a constellation, under the name metrics read it by."""
type Fact implements Node {
  constellation: Constellation
  """The alias, else the dataset's name."""
  name: String!
  """The name metrics read the dataset by; null if it's the same."""
  alias: String
  dataset: Dataset
  """How the dataset provides each role, as the fragment's `roles`, by role name."""
  roles(first: Int! = 100, after: String): AssignmentPage!
}

type FactPage {
  nodes: [Fact!]!
  endCursor: String
}

"""Another constellation a constellation imports fields from."""
type Import {
  """`*`, a field's name, or `!` and a name."""
  fields: [String!]!
  constellation: Constellation
}

"""The `JSON` scalar type represents JSON values as specified by [ECMA-404](https://ecma-international.org/wp-content/uploads/ECMA-404_2nd_edition_december_2017.pdf)."""
scalar JSON

"""A key part identifying rows by a condition, e.g. on validity."""
type KeyCondition {
  params: [KeyParameter!]!
  on: String!
}

"""A key part naming a field, whose values identify rows."""
type KeyField {
  name: String!
}

"""A placeholder of a key condition, e.g. `:as_of`."""
type KeyParameter {
  name: String!
  datatype: String
}

union KeyPart = KeyField | KeyCondition

"""An aggregatable measurement."""
type Metric implements Node {
  constellation: Constellation
  name: String!
  expr: String!
  datatype: String
  """The facts its dependencies name, e.g. `orders` for `SUM(orders.amount)`, and those of the metrics it's built from, by name. Their `roles` are how they provide roles."""
  facts: [Fact!]!
  """The metrics its dependencies name, e.g. `ordered` in `AGG(ordered) - AGG(shipped)`, as its own constellation has them."""
  metrics: [Metric!]!
}

type MetricPage {
  nodes: [Metric!]!
  endCursor: String
}

"""A markdown wiki page."""
type Page implements Node {
  name: String!
  content: String!
}

"""A value a query passes on its root table function."""
type Parameter {
  name: String!
  datatype: String
  default: String
}

"""A relationship of a dataset to an entity or a dataset, its target."""
type Relationship implements Node {
  name: String!
  """The related entity or dataset; null if it isn't defined."""
  target: RelationshipTarget
  key: [RelationshipKeyColumn!]!
  """The declared cardinality; null if it's inferred from the key."""
  cardinality: Cardinality
  """Whether every non-null key has a matching row in the target, like a foreign key."""
  alwaysMatches: Boolean!
  dataset: Dataset
}

"""How a relationship binds one of its target's fields."""
type RelationshipKeyColumn {
  name: String!
  expr: String!
}

type RelationshipPage {
  nodes: [Relationship!]!
  endCursor: String
}

union RelationshipTarget = Dataset | Entity

"""A qualitative property that metrics can be sliced by."""
type Role implements Node {
  constellation: Constellation
  name: String!
  datatype: String
  """How each fact provides the role, by the fact's name."""
  assignments(first: Int! = 100, after: String): AssignmentPage!
}

type RolePage {
  nodes: [Role!]!
  endCursor: String
}

"""A chunk of an object matching a search."""
type SearchHit {
  id: ID!
  """The chunk's heading trail in its object."""
  section: [String!]!
  text: String!
  """Relevance, higher is better, within one search."""
  score: Float!
  node: Node
}

"""A page of a search's hits, best first."""
type SearchHitPage {
  nodes: [SearchHit!]!
  """Pass as `after` for the next page; null on the last."""
  endCursor: String
  """Hits across every page."""
  totalCount: Int!
}

"""A dataset implementing an entity's key, to source its attributes."""
type Source implements Node {
  dataset: Dataset
  """How the dataset implements the entity's key."""
  on: String!
  entity: Entity
}

type SourcePage {
  nodes: [Source!]!
  endCursor: String
}

enum SourceType { TABLE SQL }
```
