Join metric views in SQL

Important

Query-time joins are in Beta.

Join metric views at query time to combine measures from independent sources, such as sales and support tickets. Use fields (also called dimensions) in the join condition, and evaluate measures with MEASURE().

Each measure retains its source grain across the join, so join fanout does not inflate its result.

Requirements

To perform query-time joins with metric views, you must meet the following requirements:

Create the example views

Suppose you want to compare sales with support workload by region. Sales and tickets are independent facts: one sale does not correspond to one ticket. Joining them on region matches each sale with every ticket in that region. Use measures to retain the sales total and ticket count without counting the repeated rows.

The examples use five sales and six support tickets. East and West have both. North has sales without tickets, and South has tickets without sales.

  1. Create the sales metric view:

    CREATE TEMPORARY VIEW sales_mv
    WITH METRICS LANGUAGE YAML AS $$
    version: 1.1
    source: |
      SELECT * FROM VALUES
        (1, 'East',  'web',   DATE'2023-12-30', 100.0),
        (2, 'East',  'store', DATE'2024-01-02', 200.0),
        (3, 'West',  'web',   DATE'2023-12-31', 150.0),
        (4, 'West',  'store', DATE'2024-01-02',  50.0),
        (5, 'North', 'web',   DATE'2024-01-03',  75.0)
      AS sales(sale_id, region, channel, sale_date, amount)
    fields:
      - name: region
        expr: region
      - name: channel
        expr: channel
      - name: sale_date
        expr: sale_date
      - name: amount
        expr: amount
    measures:
      - name: sale_count
        expr: COUNT(*)
      - name: total_sales
        expr: SUM(amount)
      - name: avg_sales
        expr: AVG(amount)
      - name: running_sales
        expr: SUM(amount)
        window:
          - order: sale_date
            range: cumulative
            semiadditive: last
    $$;
    
  2. Create the tickets metric view:

    CREATE TEMPORARY VIEW tickets_mv
    WITH METRICS LANGUAGE YAML AS $$
    version: 1.1
    source: |
      SELECT * FROM VALUES
        (1, 'East',  'high'),
        (2, 'East',  'low'),
        (3, 'East',  'low'),
        (4, 'West',  'high'),
        (5, 'West',  'low'),
        (6, 'South', 'low')
      AS tickets(ticket_id, region, severity)
    fields:
      - name: region
        expr: region
      - name: severity
        expr: severity
    measures:
      - name: ticket_count
        expr: COUNT(*)
    $$;
    
  3. Create a reference table as a temporary view for the examples that group by area:

    CREATE TEMPORARY VIEW regions AS
    SELECT * FROM VALUES
      ('East',  'Atlantic'),
      ('West',  'Pacific'),
      ('North', 'Atlantic'),
      ('South', 'Pacific')
    AS r(region, area);
    

How measures are computed across joins

The source grain describes what one source row represents. In sales_mv, each source row represents one sale. In tickets_mv, each source row represents one ticket. East has the following source rows:

sales_mv source rows:

sale_id  region  amount
-------  ------  ------
      1  East     100.0
      2  East     200.0

tickets_mv source rows:

ticket_id  region  severity
---------  ------  --------
        1  East    high
        2  East    low
        3  East    low

Joining on region matches each East sale with each East ticket. This join fanout produces six joined rows:

sale_id  region  amount  ticket_id  severity
-------  ------  ------  ---------  --------
      1  East     100.0          1  high
      1  East     100.0          2  low
      1  East     100.0          3  low
      2  East     200.0          1  high
      2  East     200.0          2  low
      2  East     200.0          3  low

The query's GROUP BY fields define the output grain. Grouping by region puts these six rows in one output group. The following query compares regular aggregates over the joined rows with measures over their contributing source rows:

SELECT
  s.region,
  SUM(s.amount) AS sum_sales,
  MEASURE(s.total_sales) AS sales,
  MEASURE(s.sale_count) AS sale_count,
  MEASURE(t.ticket_count) AS ticket_count,
  COUNT(*) AS joined_rows
FROM sales_mv s
JOIN tickets_mv t ON s.region = t.region
GROUP BY s.region
ORDER BY s.region;

The query returns the following values:

region  sum_sales  sales  sale_count  ticket_count  joined_rows
------  ---------  -----  ----------  ------------  -----------
East        900.0  300.0           2             3            6
West        400.0  200.0           2             2            4

For East, SUM(s.amount) returns 900.0, which overstates sales by a factor of three. Each sale appears three times, one for each ticket. MEASURE(s.total_sales) evaluates SUM(amount) over the two contributing sales rows and returns the correct sales total, 300.0. MEASURE(t.ticket_count) evaluates COUNT(*) over the three contributing ticket rows and returns 3.

MEASURE() removes only duplication introduced by the join. Tickets 2 and 3 have the same region and severity, but both contribute to the count. The IDs make the example rows easier to follow. This behavior does not require a declared primary key.

Combine measures from both views

Use measures from both views in an expression. The following query compares the number of support tickets with the number of sales in each region:

SELECT
  s.region,
  MEASURE(t.ticket_count) / NULLIF(MEASURE(s.sale_count), 0) AS tickets_per_sale
FROM sales_mv s
JOIN tickets_mv t ON s.region = t.region
GROUP BY s.region
ORDER BY s.region;

The query returns the following values:

region  tickets_per_sale
------  ----------------
East                 1.5
West                 1.0

Choose which groups to retain

The join type determines which rows contribute to the result. Query-time joins support the following types:

Join type Rows retained
INNER JOIN Matches from both sides.
LEFT JOIN Matches and unmatched rows from the left side.
RIGHT JOIN Matches and unmatched rows from the right side.
FULL OUTER JOIN Matches and unmatched rows from either side.
CROSS JOIN Every combination of rows from the two sides.

Use FULL OUTER JOIN to keep regions that occur in either fact source. Use COALESCE to select the region from the side that has a row:

SELECT
  COALESCE(s.region, t.region) AS region,
  MEASURE(s.total_sales) AS sales,
  MEASURE(s.sale_count) AS sale_count,
  MEASURE(t.ticket_count) AS ticket_count
FROM sales_mv s
FULL OUTER JOIN tickets_mv t ON s.region = t.region
GROUP BY COALESCE(s.region, t.region)
ORDER BY region;

The query includes North and South:

region  sales  sale_count  ticket_count
------  -----  ----------  ------------
East    300.0           2             3
North    75.0           1             0
South    NULL           0             1
West    200.0           2             2

Rows of NULL values added by an outer join do not contribute to a measure. For South, sale_count, defined as COUNT(*), returns 0. total_sales, defined as SUM(amount), returns NULL because there are no sales values to sum.

Group by a field from either view

Group by channel to compare sales with tickets from regions where that channel has sales:

SELECT
  s.channel,
  MEASURE(s.total_sales) AS sales,
  MEASURE(t.ticket_count) AS ticket_count
FROM sales_mv s
JOIN tickets_mv t ON s.region = t.region
GROUP BY s.channel
ORDER BY s.channel;

The query returns the following values:

channel  sales  ticket_count
-------  -----  ------------
store    250.0             5
web      250.0             5

The inner join excludes North because it has no tickets. East and West have sales through both channels, so their tickets contribute to both groups. A source row can contribute to more than one output group. Adding these ticket counts does not give the overall ticket count.

Filter measure results

Use WHERE to filter fields before aggregation. Use HAVING to filter evaluated measure values. The following query keeps regions whose sales exceed 250:

SELECT
  s.region,
  MEASURE(s.total_sales) AS sales,
  MEASURE(t.ticket_count) AS ticket_count
FROM sales_mv s
JOIN tickets_mv t ON s.region = t.region
GROUP BY s.region
HAVING MEASURE(s.total_sales) > 250
ORDER BY s.region;

The query returns East because its sales total is 300.0:

region  sales  ticket_count
------  -----  ------------
East    300.0             3

Join a metric view with a table or view

A query-time join can add fields from an ordinary table or view. The following query uses the temporary regions view to group sales by area:

SELECT
  r.area,
  MEASURE(s.total_sales) AS sales,
  MEASURE(s.avg_sales) AS avg_sales
FROM sales_mv s
JOIN regions r ON s.region = r.region
GROUP BY r.area
ORDER BY r.area;

The query returns the following values, with trailing decimal zeros omitted:

area      sales  avg_sales
--------  -----  ---------
Atlantic  375.0      125.0
Pacific   200.0      100.0

Filter by matching rows in another view

Use subquery predicates to filter one metric view by fields in another. Correlated references must resolve to fields. The input restrictions also apply to metric views in subqueries, including IN, EXISTS, and scalar subqueries. The following query finds sales in regions with a high-severity ticket:

SELECT s.region, MEASURE(s.total_sales) AS sales
FROM sales_mv s
WHERE EXISTS (
  SELECT 1
  FROM tickets_mv t
  WHERE t.region = s.region AND t.severity = 'high'
)
GROUP BY s.region
ORDER BY s.region;

The query returns the following values:

region  sales
------  -----
East    300.0
West    200.0

Use NOT EXISTS to find sales in regions with no tickets:

SELECT s.region, MEASURE(s.total_sales) AS sales
FROM sales_mv s
WHERE NOT EXISTS (
  SELECT 1 FROM tickets_mv t WHERE t.region = s.region
)
GROUP BY s.region;

The query returns North with sales of 75.0. Supported subquery predicates also include IN, NOT IN, ANY, ALL, and SOME.

Query window measures across a join

Window measures retain the window defined in the metric view. The running_sales measure uses a cumulative window ordered by sale_date. The following query groups by area and date:

SELECT
  r.area,
  s.sale_date,
  MEASURE(s.total_sales) AS sales,
  MEASURE(s.running_sales) AS sales_to_date
FROM sales_mv s
JOIN regions r ON s.region = r.region
GROUP BY r.area, s.sale_date
ORDER BY r.area, s.sale_date;

The cumulative total follows the dates within each area:

area      sale_date   sales  sales_to_date
--------  ----------  -----  -------------
Atlantic  2023-12-30  100.0          100.0
Atlantic  2024-01-02  200.0          300.0
Atlantic  2024-01-03   75.0          375.0
Pacific   2023-12-31  150.0          150.0
Pacific   2024-01-02   50.0          200.0

Grouping fields other than the window's order field partition the window. Here, the grouping field area comes from the joined view. For window configuration, see Advanced techniques for metric views.

Compare joins with preaggregated results

To compare measure values in a join condition, evaluate the measures in a common table expression (CTE) first. The results are ordinary scalar columns. A later join can repeat those values, and regular aggregates include those repetitions.

Choose the aggregation grain to match the question you want to answer. Preaggregating by region can change the result when the final query groups by area.

Averages

The area query above evaluates AVG(amount) across all sales in each area. For Atlantic, it returns (100 + 200 + 75) / 3 = 125.0.

The following query first evaluates the average sale in each region, then averages those results by area:

WITH regional_sales AS (
  SELECT region, MEASURE(avg_sales) AS avg_sales
  FROM sales_mv
  GROUP BY region
)
SELECT r.area, AVG(s.avg_sales) AS avg_of_regional_averages
FROM regional_sales s
JOIN regions r ON s.region = r.region
GROUP BY r.area
ORDER BY r.area;

The query returns the following values:

area      avg_of_regional_averages
--------  ------------------------
Atlantic                     112.5
Pacific                      100.0

For Atlantic, this query gives East and North equal weight by averaging their regional averages: (150 + 75) / 2 = 112.5. The average sale across Atlantic gives each sale equal weight and returns 125.0.

Window measures

Window measures also depend on the final grouping. The following query first computes running_sales separately for each region, then sums those scalar results by area and date:

WITH regional_running_sales AS (
  SELECT region, sale_date, MEASURE(running_sales) AS running_sales
  FROM sales_mv
  GROUP BY region, sale_date
)
SELECT
  r.area,
  s.sale_date,
  SUM(s.running_sales) AS sum_of_regional_running_sales
FROM regional_running_sales s
JOIN regions r ON s.region = r.region
GROUP BY r.area, s.sale_date
ORDER BY r.area, s.sale_date;

The query returns the following values:

area      sale_date   sum_of_regional_running_sales
--------  ----------  -----------------------------
Atlantic  2023-12-30                          100.0
Atlantic  2024-01-02                          300.0
Atlantic  2024-01-03                           75.0
Pacific   2023-12-31                          150.0
Pacific   2024-01-02                          200.0

On January 3, the CTE has a North row with 75.0 and no East row. Summing that day's rows omits East's accumulated 300.0. The query-time join groups by area before computing the window, so it returns 375.0 for Atlantic on January 3.

Limitations

The following restrictions apply to query-time joins:

  • Measure expressions cannot reference derived fields by name, including in FILTER (WHERE ...) predicates. Inline the field's expression using source columns instead.
  • Metric views with one-to-many YAML joins cannot be inputs, including through a composed metric-view source chain. This restriction also applies to query-time joins inside subqueries. Preaggregate the results before joining them.
  • Query-time joins do not support OpenSharing metric views or metric views composed from them.
  • An ASOF join cannot be part of the same join tree as a query-time metric view join, even when the ASOF inputs are ordinary tables.
  • BI compatibility mode does not rewrite aggregates over measure columns across joins. If your BI tool supports pass-through aggregate expressions, configure them to call MEASURE() directly. Otherwise, define the join in the metric view YAML or join preaggregated results.
  • Join conditions must be deterministic. Conditions such as ON rand() < 0.5 are unsupported.
  • Metric view columns in join conditions must be fields. A measure column such as s.total_sales cannot appear in a join condition, either on its own or inside MEASURE(). This rule also applies when USING or NATURAL JOIN selects a measure column. If the join must compare measure values, evaluate the measures in each input first. Those results are scalar columns, as described in Compare joins with preaggregated results.

SQL window expressions in measure definitions

For SQL window expressions in a metric view's measure definition (measures[].expr), query-time joins do not support the following shapes:

  • Window arguments, PARTITION BY, or ORDER BY expressions that reference unaggregated fields absent from the consuming query's GROUP BY. For example, LAG(amount) OVER (ORDER BY region) when the query groups only by region.
  • Filtered MEASURE() references alongside a window calculation or in its PARTITION BY or ORDER BY clauses. For example, MEASURE(revenue) FILTER (WHERE amount > 15) + SUM(SUM(amount)) OVER ().
  • SQL OVER combined with YAML window or partition settings on the same measure.
  • Subqueries outside aggregate inputs in the window measure's expression.

The consuming query can apply FILTER to MEASURE(...).

To apply a SQL window to evaluated measures, use an outer query over the grouped results. See Compare joins with preaggregated results.

Materializations and data freshness

Query-time joins bypass aggregated and unaggregated metric view materializations and read live source data. The queries succeed without materialization acceleration. A joined query can therefore return newer data than a standalone query served by a materialization.

Additional resources