Last reviewed: November 10, 2026 UTC (November 11 in Asia/Shanghai).
Direct answer
Keep one result row per billing row until you are ready to add up AI API costs. Sum each row’s signed credits inside that row, resolve one owner or record an unresolved owner, and then group by the dimensions the report needs. If you also need request or token metrics, aggregate both datasets to the same reporting key before joining them.
A SQL join can match one billing row to several label or usage rows. Each match carries another copy of the cost. This is called join fanout. In BigQuery, flattening two labels and two credits into the same result can turn one $10 cost into four copies, while a row with no credits can disappear. The billing export can be correct and the resulting budget alert can still be wrong.
Who this is for
Use this guide if an AI spend report changes after someone adds team ownership, credit details, or request metrics to an existing query. The worked example uses the Google Cloud standard billing export. The same accounting check applies to a normalized ledger for a direct AI API supplier: the report should account for every selected source amount once. The example amounts are fictional.
Key takeaways
- Define what one row represents at each step. A billing row, a credit, and a request attempt are different units.
- Reduce repeated credits to a signed subtotal for each billing row. Resolve ownership separately.
- Keep unassigned and conflicting ownership visible so their costs still reconcile to the source.
- Compare row counts, costs before exported credits, and signed credits before trusting the net total.
Contract details to verify
The PostgreSQL documentation on joined tables
describes the rule behind the error: an inner join produces a row for each matching pair. A left join also preserves an unmatched left row, but it still emits all matching pairs. A GROUP BY after the join therefore receives the extra copies. Changing INNER JOIN to LEFT JOIN can recover missing rows while leaving inflated totals in place.
Google’s standard billing export schema
defines cost, credits.amount, invoice.month, cost_type, and currency. Its labels field describes resource labels; project.labels describes project labels. Decide which level owns the charge before writing the query. The exported cost can already reflect negotiated pricing, so label it as cost before exported credits rather than list price.
In Google’s Cloud Billing query examples , the invoice query sums credits in a nested query for each billing row. Its label examples also show a distinction that matters for dashboards: a total for each label key and value can be useful on its own, yet the same expense can appear in both an app view and an environment view. Adding those views yields a total with overlapping costs.
Reproduce the error with two billing rows
Suppose both rows are regular costs in the same billing account, invoice month, and currency. Row A has team=support and environment=prod; row B has no labels.
| Billing row | Cost before credits | Credit amounts | Net cost |
|---|---|---|---|
| A | $10 | −$1 and −$2 | $7 |
| B | $10 | None | $10 |
| Expected total | $20 | −$3 | $17 |
If the query uses CROSS JOIN UNNEST on both arrays, A contributes four rows. Each of its two labels pairs with both credits. Summing those rows yields $40 in costs and −$6 in credits, or $34 net. B contributes no rows because its arrays are empty. This one query both multiplies and loses costs. Counting distinct dollar amounts would also fail: A and B legitimately share the same $10 amount.
Operator workflow
Pin the input and compute an independent subtotal
Use one accepted export snapshot and document its billing account, invoice month, currency, and approved AI service and SKU scope. A filtered AI workload report reconciles to the same filtered export, which may cover only part of an invoice. Record how you handle adjustments and credits that cannot be attributed to an AI workload. If the input itself overlaps an earlier export, apply the export snapshot replacement controls before diagnosing the query.
Take a baseline directly from the selected billing rows before adding any ownership join. Record the count and sum of cost by billing account, invoice month, currency, and cost type. Compute the signed credit subtotal independently, using a subquery per row or a separate credit-only aggregate. Keep each measure visible so a duplicated charge and a missing credit cannot hide behind the same net total. Use the site’s credit and adjustment classification guide
when deciding which subtotals belong in an operating cost measure.
Resolve credits and ownership without expanding the billing rows
This GoogleSQL template assumes your-project.reporting.ai_cost_scope is your own view or snapshot table with the standard export fields and the approved AI scope. Replace the table name and bind @invoice_month as a string in YYYYMM format. Before applying the template, check that selected rows have known currencies and costs and that credit elements have amounts. Resolve missing monetary fields separately so the zero below means an empty credit array. The query is a pattern to validate against your export.
WITH per_billing_row AS (
SELECT
b.billing_account_id,
b.invoice.month AS invoice_month,
b.currency,
b.cost_type,
CAST(b.cost AS NUMERIC) AS base_cost,
COALESCE((
SELECT SUM(CAST(c.amount AS NUMERIC))
FROM UNNEST(b.credits) AS c
), NUMERIC '0') AS credit_total,
(
SELECT AS STRUCT COUNT(*) AS matches, MIN(l.value) AS candidate
FROM UNNEST(b.labels) AS l
WHERE l.key = 'team'
) AS team_label
FROM `your-project.reporting.ai_cost_scope` AS b
WHERE b.invoice.month = @invoice_month
), labeled AS (
SELECT *,
CASE WHEN team_label.matches = 1
THEN NULLIF(TRIM(team_label.candidate), '')
END AS team
FROM per_billing_row
)
SELECT
billing_account_id, invoice_month, currency, cost_type,
CASE
WHEN team_label.matches = 0 THEN 'unassigned'
WHEN team IS NULL THEN 'review'
ELSE 'assigned'
END AS owner_status,
team,
COUNT(*) AS source_rows,
SUM(base_cost) AS cost_before_credits,
SUM(credit_total) AS signed_credits,
SUM(base_cost + credit_total) AS net_cost
FROM labeled
GROUP BY billing_account_id, invoice_month, currency, cost_type,
owner_status, team;
The credit subquery yields one amount per billing row. The label subquery yields one record containing the number of matching labels and a candidate value. The query uses that value only when exactly one nonblank team label exists. A repeated team key or blank value goes to review; an absent team key goes to unassigned. Include both groups when you reconcile the report. With the two sample rows, support receives $7 net and the unassigned group retains $10.
Join request metrics at the report’s level of detail
A monthly SKU cost can match hundreds of request attempts for the same workload. Even a correct cost subtotal will multiply if you attach it to each attempt and sum again. If you need cost per request, first aggregate requests to a key that both datasets can support, such as workload, model mapping, and aligned period. Aggregate costs to that same key, including currency and the agreed cost basis. Check that each input has at most one row for each actual join key, and keep unmatched cost and usage groups visible. If the cost data cannot identify a model or request reliably, report at the coarser level that it supports.
When ownership comes from a separate mapping table, check for duplicate or overlapping assignments for the same key and effective period. If a cost genuinely belongs to several owners, apply an approved split whose shares sum to one for that cost. Copying the full amount to every owner is useful only for overlapping views that are clearly labeled and never totaled together.
Verification before rollout
Run these cases against a small fixture before changing a dashboard or budget alert. They describe expected results, not production test outcomes.
| Case | Required observation |
|---|---|
| Two sample rows, with two labels and two credits on A | The enriched input still has two rows; the report sums to $20 cost, −$3 credits, and $17 net. |
A has a second team label | A appears once in review; its $7 net remains in the overall total. |
| B has no owner or credits | B contributes $10 to unassigned; no predicate drops it. |
| Another legitimate row has a $10 cost | The base total rises by $10 even though another row has the same amount. |
| A separate currency enters the export | It reconciles in its own subtotal without being added to the first currency. |
| An owner mapping matches one billing row twice | A key check detects the multiple matches before the dashboard changes. |
Compare the totals after each enrichment step, including the unassigned and review groups. When captured input rows have stable local identifiers, check that each identifier appears once in the enriched data before grouping. A matching count alone can conceal one missing row and one duplicated row. On a mismatch, isolate the smallest billing scope that changed and inspect the number of matches for its source rows. Keep the previous approved report visible with its data date until the candidate reconciles.
Failure modes
A label filter goes in WHERE after a left join. Unlabeled charges can disappear when the predicate rejects nulls. If you use a left join to pick one label key, put the key condition in ON and verify that the matching key is unique for each billing row. The scalar lookup above also keeps unmatched rows visible.
SUM(DISTINCT cost) is used to remove copies. It deduplicates values, so two legitimate $10 charges become one. Fix the join that produced the copies and preserve the original rows.
Only net cost is checked. Duplicated positive costs and duplicated negative credits can offset each other. Reconcile the row count and both signed components before examining net cost.
Sources checked
- PostgreSQL 18: Table Expressions — official reference for join cardinality, outer join filters, and grouping. The current documentation was serving version 18 when checked.
- Google Cloud: Structure of Standard data export — official definitions of cost, credits, labels, billing scope, and currency; last updated November 4, 2026 UTC.
- Google Cloud: Example queries for Cloud Billing data export — official examples of per-row credit sums, label grouping, and double counting across label keys; last updated November 4, 2026 UTC.
All three pages returned HTTP 200 on November 10, 2026 UTC. They describe the current technical contracts used in this guide. The example query and acceptance cases apply those contracts to a proposed reporting control.
FAQ
What if I only need to know whether a billing row has a label?
Use an EXISTS subquery against the label array. It tests membership once per billing row even if several elements match. Apply the same membership filter to your comparison baseline if the report intentionally excludes unlabeled rows.
Can I show costs by both team and environment?
Yes. Resolve one team and one environment per billing row, then group by that pair for a single additive view. If you also show separate team totals and environment totals, reconcile each view independently; adding them counts the same costs again.
Can a billing export row tell me the price of one request?
Only when you have evidence linking that row to the request at the required level of detail. Otherwise, use an aggregate cost per request with a matched scope and period, or show the two measures separately if the mapping is incomplete.
Reader next step
Pick one AI billing report that recently gained a label or usage join. Pin one invoice month and currency, compute the source count and signed subtotals, and compare them after each join. Add the two-row fixture to your report checks. Approve the revised query once the assigned, unassigned, and review buckets account for the same selected costs and credits.