> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Joins and aggregates

Resolve an endpoint with `ctx.get` and a bounded inverse with `ctx.list` on
an index that serves it. A query combines those results at one version and
returns a projection. Keep every selection bounded with `.first(n)`, or page
it.

## Maintained totals

For counts and exact sums per group, declare a `total` on the table. The host
maintains it on every write, so a read never scans the facts:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { query, role, t, table } from "@bijectionhq/bijection";

export const customers = table({ name: t.string });

export const orders = table(
  { customer: t.key(customers), region: t.string, amount: t.decimal, quantity: t.int },
  {
    index: [["region", "customer"]],
    total: [{ group: ["region", "customer"], sum: { amount: 2, quantity: 0 } }],
  },
);

export const orderTotals = query({
  allow: [role.signedIn], args: { region: t.string, customer: t.key(customers) },
}, async (ctx, { region, customer }) => {
  const [group] = await ctx.get(orders.where({ region, customer }).total());
  // One entry per customer in the region.
  const byCustomer = await ctx.get(orders.where({ region }).total());
  return { group: group ?? null, byCustomer };
});
```

* `group` names one to four fields. `.total()` answers the groups whose
  `group` starts with the `.where` fields, each `{ key, count, sum }`.
* `sum` maps `t.decimal` fields to their fixed scale and `t.int` fields to
  `0`. The sums are exact: a `Decimal` or a `bigint`.
* `erased: true` keeps counting facts after they are erased, and sums
  nothing.

A `.total()` that no declared total serves is refused with the `total` to add.
`ctx.count(selection)` is always exact as well, but reads the selection.

For an aggregation beyond that, compute and publish a result with
[Pipelines](https://docs.bijection.com/transforms/pipelines.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.