Skip to content

SquareX recipes

Every recipe below is a complete, working set of measures — copy it into the measure editor and swap in your own table and column names. To create a measure: open your model, click ƒx Measures in the toolbar, then New measure. Paste into the Code tab (or build the same shape from a template), watch the diagnostics, and check the compiled-SQL preview before saving.

Recipes assume a small sales model — Sales(OrderId, CustomerId, Amount, Qty, Price, Cost, Region), a Product table, and a date column Date.Date — adjust freely.

Almost every dashboard starts with these three. Build the small ones first; everything else references them.

Recipe · KPI starter pack
Revenue := Sum(Sales.Amount)
Orders := CountDistinct(Sales.OrderId)
AvgOrderValue := Divide([Revenue], [Orders])

Use them on: KPI cards for the headline numbers; any chart’s value well. They aggregate correctly at whatever grain the chart applies — [Revenue] by month, by region, by product all come from this one definition.

An aggregate over zero rows is blank (NULL), which renders as an empty cell. When a zero communicates better:

Recipe · zero instead of blank
RevenueOrZero := Coalesce([Revenue], 0)

Use it on: tables and matrix visuals where empty groups should read as 0. Keep the blank-returning original for cards where no data and zero revenue mean different things.

The standard trio: this year, last year, growth.

Recipe · year-over-year
Revenue := Sum(Sales.Amount)
RevenueLY := Calculate([Revenue], DateShift(Date.Date, -1, "year"))
YoYGrowthPct := Divide([Revenue] - [RevenueLY], [RevenueLY])

Use them on: a line chart by Date.Date:month with [Revenue] and [RevenueLY] as two series; [YoYGrowthPct] on a KPI card (format as %) or as a tooltip field. The shift is computed on raw dates before bucketing, so week-grain charts stay correct too. Swap -1, "year" for -1, "quarter" or -1, "month" for QoQ/MoM.

Recipe · YTD vs prior-year YTD
RevenueYTD := YTD([Revenue], Date.Date)
// Last year's accumulation, aligned onto this year's buckets
RevenueYTDLY := Calculate([RevenueYTD], DateShift(Date.Date, -1, "year"))
YTDvsLYPct := Divide([RevenueYTD] - [RevenueYTDLY], [RevenueYTDLY])

Use them on: a line chart by Date.Date:month — the two YTD lines make the classic pacing chart; the gap between them is the story. The chart must group by the measure’s date column (SQX010 tells you if it doesn’t). QTD and MTD are drop-in replacements at quarter/month scope — chart MTD on a day axis.

Smooths seasonality better than any calendar-year cut:

Recipe · trailing 12 months
Revenue12mRolling := RollingSum([Revenue], 12, "month")

Use it on: a line chart by Date.Date:month. Months with no sales count as zero — the window never silently shrinks. Filter the chart’s date range freely; the look-back still reaches behind the filter so the first visible points are correct.

Recipe · % of total
PctOfTotalRevenue := Divide(
[Revenue],
Calculate([Revenue], RemoveFilters(Product))
)

Use it on: a bar chart or table grouped by product — every row divides by the product-spanning total, so the column sums to 100%. List every dimension the chart groups by in RemoveFilters(…); or use RemoveFilters() bare for a denominator that also ignores slicers (the true grand total).

When the chart groups by month and region and you want each region’s share of its month, exclude just the region level; the denominator keeps following every other axis the viewer adds:

Recipe · % of subtotal
MonthTotal := Exclude(Sales.Region, [Revenue])
PctOfMonth := Divide([Revenue], [MonthTotal])

Use it on: a stacked bar by month split by region, or a matrix with months as rows and regions as columns. Unlike the RemoveFilters recipe, nothing is hard-coded to month — regroup by quarter and the subtotal follows.

Compare any slice against a fixed reference, no matter what the viewer filters:

Recipe · fixed benchmarks
// All-regions figure, immune to a Region slicer
RevenueAllRegions := Calculate([Revenue], RemoveFilters(Sales.Region))
// A pinned segment — the override idiom (remove, then add)
WestRevenue := Calculate([Revenue], Sales.Region = "West", RemoveFilters(Sales.Region))
PctVsWest := Divide([Revenue], [WestRevenue])

Use them on: KPI cards side by side (your selection vs all vs West), or as a constant reference series on a line chart. Why the remove-then-add works regardless of written order: removals apply first.

The average of a per-entity total — not the average line amount:

Recipe · per-customer revenue
CustomerRevenue := Fixed(Customer.Id, [Revenue])

Use it on: any chart, with the field-well aggregation set to avg — by-region bars give average revenue per customer per region; max gives the biggest customer per region. Prefer Include(Customer.Id, [Revenue]) when the grain should adapt to whatever the viewer groups by rather than being pinned.

Recipe · monthly active customers
CustomersPerMonth := Fixed(Date.Date:month, CountDistinct(Sales.CustomerId))

Use it on: a line chart by Date.Date:month, or aggregate it (avg) for a typical month KPI card. The inline :month grain replaces the usual date-truncation boilerplate.

Means hide skew; medians and percentiles show it:

Recipe · distribution cutoffs
MedianOrderValue := Median(Sales.Amount)
P90OrderValue := Percentile(Sales.Amount, 0.9)

Use them on: KPI cards next to [AvgOrderValue] — a mean far above the median is itself a finding — or a bar chart by segment for SLA-style reporting (P90 delivery days, P95 response time). Both are dialect-gated: not available on MySQL, SQL Server, or BigQuery sources (the support matrix has each engine’s exact behavior), and neither can be accumulated by YTD/RollingSum.

When the math must happen per row before summing, use an iterator:

Recipe · weighted price
GrossRevenue := SumX(Sales, Sales.Qty * Sales.Price)
WeightedPrice := Divide(SumX(Sales, Sales.Qty * Sales.Price), Sum(Sales.Qty))

Use them on: anywhere a plain Avg(Sales.Price) would mislead — the weighted price weights big orders properly. Inside the row expression, only bare columns of the iterated table are allowed (SQX014 guards the rest).

Recipe · basket size
LinesPerOrder := Divide(CountRows(Sales), CountDistinct(Sales.OrderId))

Use it on: a KPI card or a trend line by month — a rising basket size changes how you read flat order counts.

Stock levels, account balances, and headcount are levels, not flows — summing them over time is meaningless. Take the value at the last date that has one:

Recipe · current balance
ClosingStock := LastNonEmpty(Sum(Inventory.OnHand), Inventory.CountedAt)

Use it on: a KPI card (the current level, whatever date it landed on) or grouped by warehouse — each group picks its own last non-empty date. Add a filter with Calculate to ask as of within that filter: the pick moves with it.

Recipe · month-end snapshot
EOMStock := PeriodEndSnapshot(Sum(Inventory.OnHand), Inventory.CountedAt, "month")

Use it on: a line chart grouped by Inventory.CountedAt:month — the axis grain must match the snapshot grain (SQX010 enforces it). Each bucket shows the last reading inside it: the classic closing-balance trend.

Banding on measure values — searched conditions, first true wins:

Recipe · account tiers
RevenueTier := Case(
[Revenue] >= 1000000, "Tier 1",
[Revenue] >= 100000, "Tier 2",
"Tier 3")

Use it on: tables and matrices as a computed label column, or a KPI card’s secondary value. Banding on a column (e.g. Sales.Segment) is row logic and belongs in a calculated field instead — SQX014 will point you there.

Recipe · KPI subtitle
RevenueLabel := "Total: " & ToText(Round([Revenue], 0))
AsOfLabel := "as of " & ToText(Max(Sales.OrderDate))

Use them on: KPI cards and text tiles. & takes strings only — ToText does the conversion explicitly (no silent coercion, SQX006).

Recipe · margin %
MarginPct := Let(rev, [Revenue],
Divide(rev - Sum(Sales.Cost), rev))

Use it on: KPI cards and by-product bars (format as %). Let computes the bound expression once in the compiled SQL — cleaner to read, cheaper to run. Let measures are code-lane only; the template builder shows them read-only.