The course began with a discrepancy: in October 2026, Marketing reported €3,720,000 in sales and Finance, €2,828,429.75. Neither department made a mistake in adding up. Each had written its own definition of "sales" in its own tool. Requirement RQ-11 was born from that: a single definition of each metric, implemented in one place.
The previous modules have moved toward that requirement: the glossary fixes the meaning (POL-04) and the consumption.daily_net_sales table implements one metric. But ADR-013 has just left a question open: if metrics are not defined in the BI tool, then where? With a single metric, a table is enough. With ten metrics, five dimensions and three tools, you need a component with a name of its own: the semantic layer.
This lesson explains what problem it solves, what parts it consists of, what traps metric aggregation hides, what options there are for implementing it and which one DataCorp chooses. We will define its official metrics as code and see how their lifecycle is governed.
The problem: the same metric, recalculated in every report
A metric such as net sales is not a stored piece of data: it is a recipe. You have to decide which amount is summed (with or without VAT), which orders count (cancelled ones? returned ones?), which date they are assigned to (order, payment or delivery) and in which time zone. Each decision has several reasonable answers.
Without a semantic layer, the recipe is rewritten in every place where it is needed: in the query of a dashboard, in the formula of a spreadsheet, in a notebook. Three consequences:
- Divergence. It only takes one copy forgetting to exclude returned orders for two figures to appear. With dozens of reports, it is a matter of time.
- Impossible changes. If Finance decides that orders pending payment do not count either, every copy has to be located and modified. One always gets left behind.
- Distrust. When two dashboards do not agree, the meeting stops being about the business and starts being about who has the right figure. It was one of the costs of disorder estimated in lesson 01-02.
The glossary settles the meaning, but a glossary is a document: nothing prevents a query from contradicting it. The semantic layer turns the definition into something executable: the recipe is written once, and everyone who needs the metric gets it from there.
What a semantic layer is and where it sits
A semantic layer is the component that translates physical data (tables, columns, keys) into business concepts (metrics, dimensions) and guarantees that each concept is always calculated the same way, whoever asks for it. It sits between the consumption zone and the tools:
flowchart LR
C[("Consumption zone<br/>facts and dimensions")] --> S["Semantic layer<br/>metrics, dimensions,<br/>aggregation rules"]
S --> BI["BI tool"]
S --> SQL["SQL and notebooks"]
S --> APP["Applications"]
G["Glossary (POL-04)<br/>meaning and owner"] -. "defines" .-> S
The consumer stops asking for "sum net_amount from fact_sales, joining with dim_date and filtering statuses" and starts asking for "net sales by category and month". The semantic layer knows which tables to join, which filters to apply and how to aggregate.
It is worth distinguishing it from its neighbors:
| Component | What it contains | For whom |
|---|---|---|
| Glossary (lesson 03-01) | The meaning of each term, in natural language | People |
| Dimensional model (lesson 02-05) | Fact tables and dimensions: the data | The engine |
| Semantic layer | The executable formula of each metric and its aggregation rules | Tools |
Components of a semantic layer
Every implementation shares the same parts, under slightly different names:
| Component | What it is | Example at DataCorp |
|---|---|---|
| Entity | The business object that a key identifies and that lets tables be related | Order (order_id), customer, product, campaign |
| Dimension | An attribute to filter or group by | Category, city, order status, campaign channel |
| Time dimension | The date the metric is assigned to, with its granularity | Order date: day, week, month, quarter, year |
| Measure | An elementary aggregation over a column | SUM(net_amount), COUNT(DISTINCT order_id) |
| Metric | The business indicator, built from one or more measures | Net sales, average order value, ROAS |
| Hierarchy | Ordered levels of a dimension, for drilling down and rolling up | Product → category; day → month → year |
Metrics, in turn, come in four types:
| Type | Definition | Example |
|---|---|---|
| Simple | One measure, perhaps with a filter | Net sales = sum of the net amount of valid orders |
| Derived | An expression over other metrics | Cancelled and returned orders = total orders − valid orders |
| Ratio | The quotient of two metrics | Average order value = net sales / valid orders |
| Cumulative | A metric summed over a time window | Month-to-date net sales; sales of the last 28 days |
Time granularity deserves a warning. "Net sales for the week" requires deciding whether the week starts on Monday, and "for the month" depends on the time zone: an order placed at 00:30 on November 1 in Madrid is still October 31 in UTC. DataCorp already settled this in lesson 03-05 with the business date in Europe/Madrid; the semantic layer is the place where that decision is applied to all metrics alike.
Additivity: the traps of aggregating metrics
Lesson 02-05 classified measures as additive, semi-additive and non-additive. In the semantic layer that classification stops being theory, because BI tools re-aggregate constantly: every time the user removes a dimension or switches from day to month, the tool aggregates what it has again. If the metric does not allow it, the result is wrong and nothing warns you.
Trap 1: distinct counts
daily_net_sales has one row per day, category and city, and its num_orders column counts the distinct orders of that combination. An order with a vacuum cleaner (Home) and a pair of headphones (Electronics) appears in two rows.
-- WRONG: sums a distinct count across categories
SELECT SUM(num_orders) AS orders
FROM consumption.daily_net_sales
WHERE sales_date >= DATE '2026-10-01' AND sales_date < DATE '2026-11-01';
-- Result: 47,914 (12% more than the actual figure)
-- RIGHT: count on the detail, where each order is identifiable
SELECT COUNT(DISTINCT s.order_id) AS orders
FROM consumption.fact_sales s
JOIN consumption.dim_date d ON d.date_sk = s.date_sk
WHERE d.year_number = 2026 AND d.month_number = 10
AND s.order_status NOT IN ('cancelled', 'returned');
-- Result: 42,780The difference of 5,134 orders is the repeated counting of the orders with products from more than one category. The num_orders column is not wrong: it correctly answers "how many orders included something from Home?". What is wrong is summing it.
The underlying solution is to have the count at a grain where it is additive. An order belongs to a single customer and a single day, so at the day × city grain each order appears once. For this purpose DataCorp adds a second aggregate table:
-- consumption.daily_orders: day x city grain. All of its columns can be summed.
SELECT d.full_date AS order_date,
c.city,
COUNT(DISTINCT s.order_id) AS total_orders,
COUNT(DISTINCT CASE WHEN s.order_status NOT IN ('cancelled', 'returned')
THEN s.order_id END) AS valid_orders,
ROUND(SUM(s.gross_amount), 2) AS gross_sales,
ROUND(SUM(CASE WHEN s.order_status NOT IN ('cancelled', 'returned')
THEN s.net_amount ELSE 0 END), 2) AS net_sales
FROM consumption.fact_sales s
JOIN consumption.dim_date d ON d.date_sk = s.date_sk
JOIN consumption.dim_customer c ON c.customer_sk = s.customer_sk
GROUP BY d.full_date, c.city;The CASE inside the aggregation makes it possible to calculate, in a single pass, the metrics with and without the status filter. A nuance: unique customers would still not be summable across days, because a customer can buy on several days; for them, only the detail will do.
Trap 2: ratios are neither averaged nor summed
A ratio is a quotient, and the quotient of the sums is not the average of the quotients. Take an example with return on ad spend (ROAS): the net sales attributed to a campaign divided by its cost. Sample figures for three campaigns:
| Campaign | Channel | Cost | Attributed net sales | ROAS |
|---|---|---|---|---|
BF26-ELECTRO |
Paid search | 42,000.00 | 189,000.00 | 4.50 |
BF26-HOGAR |
Social media | 30,000.00 | 81,000.00 | 2.70 |
NAV26-EMAIL |
3,000.00 | 36,000.00 | 12.00 | |
| Total | 75,000.00 | 306,000.00 | 4.08 |
The average of the three ROAS values is 6.40; the actual ROAS of the set is 306,000 / 75,000 = 4.08. The e-mail campaign, with a minimal cost, distorts the average. The rule: a ratio is stored as its two additive components and divided at the end, after aggregating. That is why daily_orders has no avg_order_value column.
Trap 3: joining facts of different grain
ROAS combines two fact tables: fact_sales (one row per order line) and fact_campaigns (one row per campaign and day, with its cost). Joining them directly multiplies the rows:
-- WRONG: the daily cost is repeated for every order line of the campaign
SELECT dc.campaign_code,
SUM(s.net_amount) / SUM(fc.cost_amount) AS roas
FROM consumption.fact_sales s
JOIN consumption.fact_campaigns fc
ON fc.campaign_sk = s.campaign_sk AND fc.date_sk = s.date_sk
JOIN consumption.dim_campaign dc ON dc.campaign_sk = s.campaign_sk
GROUP BY dc.campaign_code;
-- RIGHT: each fact is aggregated separately to the common grain, and then they are joined
WITH sales AS (
SELECT campaign_sk, SUM(net_amount) AS attributed_net_sales
FROM consumption.fact_sales
WHERE order_status NOT IN ('cancelled', 'returned')
AND campaign_sk <> 0 -- 0 = "No attributed campaign"
GROUP BY campaign_sk
),
costs AS (
SELECT campaign_sk, SUM(cost_amount) AS campaign_cost
FROM consumption.fact_campaigns
GROUP BY campaign_sk
)
SELECT dc.campaign_code,
ROUND(s.attributed_net_sales / NULLIF(c.campaign_cost, 0), 2) AS roas
FROM costs c
JOIN consumption.dim_campaign dc ON dc.campaign_sk = c.campaign_sk
LEFT JOIN sales s ON s.campaign_sk = c.campaign_sk;In the wrong version, if a campaign had 400 order lines on one day, its cost for that day is added 400 times and the ROAS collapses. The right one applies the technique that lesson 02-05 called joining facts through conformed dimensions: aggregate each fact to a shared grain (here, the campaign) and join afterward. NULLIF(c.campaign_cost, 0) avoids division by zero, and the LEFT JOIN keeps the campaigns with a cost and no sales, which are precisely the ones worth detecting.
A well-built semantic layer knows the grain of each table and always generates the second query. That is its greatest practical contribution.
Implementation options
There are three ways of implementing a semantic layer. They are not mutually exclusive: most organizations combine two.
| Tables and views in the store | The BI tool's semantic model | Standalone semantic layer | |
|---|---|---|---|
| What it consists of | Metrics are materialized in aggregate tables or views | They are defined in the tool's model (LookML, Power BI's tabular model) | A dedicated service receives metric requests and generates the SQL |
| Examples | dbt models in consumption |
Looker, Power BI | dbt Semantic Layer (MetricFlow), Cube |
| Who consumes it | Any tool that speaks SQL | That tool only | Any tool with a connector |
| Flexibility | Only the combinations anticipated in the grain of each table | High within the tool | High: any dimension and granularity |
| Ratios and non-additive metrics | You have to divide at query time | Solved | Solved |
| Operation | None additional | None additional | One more component to deploy and monitor |
| Risk | Proliferation of aggregate tables | Dependence on the tool; other tools are left out | Complexity; uneven support in BI tools |
In both the second and the third option the definitions can be written in versioned text files. That practice is known as metrics as code: metrics are treated just like transformations, with version control, peer review, automated tests and controlled deployment. It is the same idea that ADR-005 applied to governance and ADR-009 to transformations.
The criterion for choosing is the number of different consumers. With a single BI tool and a handful of metrics, tables in the store are enough. With several tools, applications that consume metrics and dozens of definitions, the standalone layer pays for itself.
DataCorp's official metrics
The data governance committee approves the first set of official metrics. Each one links to a glossary term and has an owner, who is the person accountable for its definition.
| Metric | Type | Definition | Additive | Owner | October 2026 |
|---|---|---|---|---|---|
gross_sales |
Simple | Sum of the amount including VAT of all orders | Yes | Carmen Ruiz | €3,720,000.00 |
net_sales |
Simple | Sum of the amount excluding VAT of valid orders | Yes | Carmen Ruiz | €2,828,429.75 |
total_orders |
Simple | Number of distinct orders | By day and city | Carmen Ruiz | 46,500 |
valid_orders |
Simple | Orders neither cancelled nor returned | By day and city | Carmen Ruiz | 42,780 |
avg_order_value |
Ratio | net_sales / valid_orders |
No | Carmen Ruiz | €66.12 |
cancellation_rate |
Ratio | (total_orders − valid_orders) / total_orders |
No | Carmen Ruiz | 8.00% |
campaign_cost |
Simple | Sum of the cost of the campaigns | Yes | Nuria Vidal | — |
attributed_net_sales |
Simple | Net sales of the orders with an attributed campaign (ADR-008) | Yes | Nuria Vidal | — |
roas |
Ratio | attributed_net_sales / campaign_cost |
No | Nuria Vidal | — |
Notes:
cancellation_rateis the official name of the cancellation and return rate: the proportion of orders that do not end up being a valid sale. In October, 3,720 out of 46,500.- The three campaign metrics have no value for October because orders only record their campaign since the
campaign_codecolumn has existed; earlier ones belong to "No attributed campaign". - ROAS is not a profit. A ROAS of 4.08 means €4.08 of net sales for every euro invested, not of margin: the platform does not yet have the cost of the products. The metric's datasheet must say so, so that nobody reads it as net profitability.
- Average order value, cancellation rate and ROAS are added to the glossary (
governance/glossary.yaml) as part of this registration.
To serve them, the consumption model is completed with dim_campaign(campaign_sk, campaign_code, name, channel, start_date, end_date), fact_campaigns(date_sk, campaign_sk, impressions, clicks, cost_amount), the campaign_sk column in fact_sales and two new aggregate tables: daily_orders, already seen, and daily_campaigns(campaign_date, campaign_code, channel, cost_amount, attributed_orders, attributed_net_sales).
Metrics as code: definition in YAML
The definitions are written in YAML files inside the datacorp-data repository. The format follows, in simplified form, that of dbt's semantic models (MetricFlow): first the table is described (entities, dimensions and measures) and then the metrics built on it.
# datacorp-data/metrics/sales.yaml (simplified syntax)
semantic_models:
- name: sales
model: ref('fact_sales') # grain: order line
entities:
- {name: line, type: primary, expr: line_id}
- {name: order, type: foreign, expr: order_id}
- {name: customer, type: foreign, expr: customer_sk}
- {name: product, type: foreign, expr: product_sk}
- {name: campaign, type: foreign, expr: campaign_sk}
dimensions:
- {name: sales_date, type: time, granularity: day} # business date (Europe/Madrid)
- {name: order_status, type: categorical}
measures:
- name: total_gross_amount
agg: sum
expr: gross_amount
- name: valid_net_amount
agg: sum
expr: "case when order_status not in ('cancelled','returned') then net_amount else 0 end"
- name: num_orders
agg: count_distinct # the layer knows it cannot be summed
expr: order_id
- name: num_valid_orders
agg: count_distinct
expr: "case when order_status not in ('cancelled','returned') then order_id end"
metrics:
- name: net_sales
label: Net sales
type: simple
measure: valid_net_amount
meta: {glossary: net_sales, owner: [email protected],
version: 1.0.0, status: certified, unit: EUR}
- name: avg_order_value
label: Average order value
type: ratio
numerator: net_sales # each part is aggregated and divided at the end
denominator: valid_orders
meta: {glossary: avg_order_value, owner: [email protected],
version: 1.0.0, status: certified, unit: EUR}
- name: cancellation_rate
label: Cancellation and return rate
type: derived
expr: (total_orders - valid_orders) / total_orders
metrics: [total_orders, valid_orders]
meta: {glossary: cancellation_rate, owner: [email protected],
version: 1.0.0, status: certified, unit: percentage}
- name: roas
label: Return on ad spend (ROAS)
type: ratio
numerator: attributed_net_sales # net_sales with the filter campaign <> 0
denominator: campaign_cost # measure of the 'campaigns' semantic model
meta: {glossary: roas, owner: [email protected],
version: 1.0.0, status: certified,
note: "On net sales, not on margin"}How to read it:
semantic_modelsdescribesfact_salesin business terms. The entities indicate which keys it can be joined on; that way the layer knows how to reach the category throughproductwithout anyone writing theJOIN.measuresare the elementary aggregations. The status filter appears here and nowhere else: it is the single implementation that RQ-11 requires.agg: count_distinctdeclares that the count cannot be summed; the layer recalculates it from the detail every time.metricsbuilds the indicators. Inavg_order_value, of typeratio, numerator and denominator are aggregated separately.gross_sales,total_orders,valid_orders,attributed_net_salesandcampaign_costare defined in the same way and are omitted for brevity.metalinks to governance: glossary term, owner, version and status. The validatorgovernance/validate_datasheets.pychecks on every change that each metric has a term and an owner.
The metric tree
Metrics are not a flat list: some break down into others. A metric tree represents that breakdown, from the indicator that matters to Management down to the levers that someone can act on.
flowchart TD
NS["Net sales<br/>€2,828,429.75"] --> VO["Valid orders<br/>42,780"]
NS --> AOV["Average order value<br/>€66.12"]
VO --> TOT["Total orders<br/>46,500"]
VO --> CR["Cancellation rate<br/>8.00%"]
TOT --> WS["Web sessions<br/>(UC-04)"]
TOT --> CVR["Conversion rate<br/>(UC-04)"]
AOV --> UPO["Units per order"]
AOV --> AUP["Average price per unit"]
It reads as an identity: net sales = valid orders × average order value, and valid orders = total orders × (1 − cancellation rate). In October, 46,500 × 0.92 × €66.12 ≈ 2.83 million.
The tree has three uses. It guides diagnosis: if net sales fall, you go down the branches until you find which one has moved. It assigns responsibilities: the cancellation rate has different levers (product quality, logistics) from conversion (website, campaigns). And it reveals gaps: the two leaves marked UC-04 do not exist yet, and without them you cannot explain why orders vary.
Lifecycle, governance and certification
An official metric is an asset with an owner, and it changes with the business. Its lifecycle has three moments:
| Moment | What happens | Who is involved |
|---|---|---|
| Registration | A proposal with name, definition, formula, owner and intended use. It is checked that it does not duplicate an existing one. It is added to the glossary and to the YAML in the same change, with its tests | Proposer → domain steward → owner (approves) → data team (implements) |
| Change | Every modification of the formula increments the version. A change that alters the figures is a major version: it is announced, an effective date is set and it is decided whether the history is recalculated | Owner (decides) → committee (informed) |
| Retirement | It is marked as deprecated with an end date, the owners of the dashboards that use it are notified (the lineage says which ones) and, once the period has passed, it is removed |
Owner and data team |
The change is the delicate moment. If in March 2027 net sales start excluding orders pending payment, there are two honest options: recalculate the whole history with the new definition (the series remain comparable, but figures already published change) or keep both during a transition (net_sales and net_sales_v2), with a visible note on the dashboards. The one that is not acceptable is the third: changing the formula silently and leaving a series with a step that nobody will be able to explain a year later.
Certification extends the idea to datasets. A consumption table is marked as certified in its datasheet (governance/datasheets/consumption.<table>.yaml) when it meets five conditions:
- It has an owner and a steward.
- It is documented in the catalog, column by column, with its grain and its aggregation rules.
- Its quality tests (DQ rules) run on every load and pass.
- It has a freshness commitment (07:00 for the nightly loads).
- Its metrics correspond to approved glossary terms.
In the BI tool, certified tables are published in an official collection with a visible badge. The rule of use is the one announced in lesson 05-01: explore with whatever you like; publish for Management with certified data only.
ADR-014: DataCorp's semantic layer
DataCorp has a single BI tool (ADR-013), nine official metrics and two people. A standalone semantic layer would be one more component to operate for a single consumer. But leaving the definitions only in aggregate tables would make them hard to move on the day it became necessary.
ADR-014: Semantic layer: metrics as code, materialized in certified
tables of the consumption zone
Status: accepted Date: 2026-12-09
CONTEXT
RQ-11 requires a single definition of each metric, implemented in one
place. ADR-013 sets a single BI tool, with a lightweight semantic model,
and establishes that metrics are not defined in it. Transformations are
already managed with dbt Core (ADR-009).
DECISION
1. Each official metric is defined only once, in YAML, in
datacorp-data/metrics/, in the format of dbt's semantic models,
linked to its glossary term and its owner.
2. Metrics are materialized with dbt in certified aggregate tables in
consumption: daily_net_sales (day x category x city), daily_orders
(day x city) and daily_campaigns (day x campaign).
3. Aggregate tables store only additive components. Ratios
(avg_order_value, cancellation_rate, roas) are not stored: they are
calculated at query time as a quotient of sums.
4. In the BI tool, ratios are defined only once as metrics of the
official collection, transcribed from the YAML and editable only by
the data team. No other calculated metrics are created in published
dashboards.
5. An automated test reconciles the aggregate tables with the detail
(fact_sales) every night, as an extension of rule DQ-08.
6. Registration, change and retirement of metrics follow the
repository's change workflow, with the owner's approval. Changes of
definition increment the major version.
ALTERNATIVES CONSIDERED
A. Define the metrics in the BI tool's model. Rejected: SQL and
notebooks would be left out, and the metrics tied to the tool.
B. Standalone semantic layer (dbt Semantic Layer service or Cube).
Deferred: one more component or paid service for a single consumer
(RQ-12, RQ-13).
CONSEQUENCES
Positive: no new components; every tool reads the same tables; the
definitions are portable to a standalone layer.
Negative: only the combinations anticipated in the grain of each table
are served; ratios have a second transcription in the BI tool, which
has to be kept in sync.
REVIEW CONDITIONS
- A second consumer of metrics appears (another tool or an
application).
- 30 official metrics or 8 aggregate tables are exceeded.Common Mistakes and Tips
- Storing ratios in aggregate tables. An
avg_order_valueper row will end up being averaged. Store numerator and denominator. - Summing distinct counts. Orders by category, customers by day: always check at which grain they can be summed.
- Metrics with the same name and a different meaning, or the opposite. Plain "sales" was the origin of the problem; the name of the metric must be the glossary term.
- Changing a definition without versioning it. It leaves inexplicable historical series.
- Too many metrics or too many aggregate tables. A hundred "official" metrics amount to none; hence the limits in ADR-014.
- Tip: for each metric, write a check query with a known result (October 2026: €2,828,429.75) and turn it into an automated test.
- Tip: also document what the metric is not. "ROAS does not deduct the cost of the product" prevents more misunderstandings than the formula does.
Exercises
Exercise 1: Can it be summed?
For each column, state whether it can be summed along the given dimension and why:
net_salesindaily_net_sales, across categories.valid_ordersindaily_orders, across days.- Distinct customers who bought each day, across the days of a month.
stock_unitsinfact_daily_inventory, across days.- ROAS of each campaign, across campaigns.
Exercise 2: Monthly average order value by city
Write a query on consumption.daily_orders that returns the average order value and the cancellation rate for October 2026 by city. Explain why AVG must not be used.
Solutions
Exercise 1
- Yes. It is a sum of amounts; each order line belongs to a single category.
- Yes. Each order has a single date and a single city: it appears only once.
- No. A customer who buys on three days would be counted three times. You have to count distinct values on the detail for the whole month.
- No. It is semi-additive: a month's stock is not the sum of the daily snapshots. It is summed across products or warehouses, and across days you take the last value or the average.
- No. It is a ratio: you add up the attributed sales and the cost, and then divide.
Exercise 2
SELECT city,
ROUND(SUM(net_sales) / NULLIF(SUM(valid_orders), 0), 2) AS avg_order_value,
ROUND(100.0 * (SUM(total_orders) - SUM(valid_orders))
/ NULLIF(SUM(total_orders), 0), 2) AS cancellation_rate_pct
FROM consumption.daily_orders
WHERE order_date >= DATE '2026-10-01' AND order_date < DATE '2026-11-01'
GROUP BY city
ORDER BY avg_order_value DESC;First the components for the whole month are summed, and then the division is done. With AVG(net_sales / valid_orders) you would get the mean of the daily average order values, in which a Sunday with 20 orders weighs the same as a Monday with 200. The 100.0 forces decimal division and NULLIF avoids dividing by zero in a city with no orders.
Conclusion
A metric is a recipe, and without a single place to write it down it ends up copied, with variations, in every report: that is the origin of contradictory figures. The semantic layer sits between the consumption zone and the tools, and turns the glossary definitions into executable formulas, built from entities, dimensions, measures and simple, derived, ratio and cumulative metrics. Its most delicate task is aggregating correctly: distinct counts are not summed, ratios are calculated as a quotient of sums and facts of different grain are aggregated before being joined. It can be implemented with tables in the store, with the BI tool's model or with a standalone layer, and in every case it pays to treat metrics as code. In ADR-014, DataCorp has set nine official metrics, defined in YAML and materialized in three certified aggregate tables, with a lifecycle governed by their owners.
As a result, the net sales figure is the same wherever it is queried from. But a correct figure can still be communicated badly: a truncated axis, a poorly chosen color or a dashboard with forty indicators can lead to a wrong decision with impeccable data. The next lesson deals with that last step: data visualization.
