
Weighted averages and running totals
A weighted grand total must come from the original numerator and denominator, not an average of visible averages.
A sales Pivot table shows 600 for North on page one. The grand total should still be 1,400, even when only one region is visible. To keep it correct, calculate totals from the entire filtered dataset in SQL, then fetch the requested page of aggregate rows.
This Node.js and SQLite example connects RevoGrid Pivot to /api/pivot/load. SQLite groups sales by region and quarter, applies the sales-channel filter, and sends the cells and axis metadata that Pivot uses to build the grid.
JavaScript Pivot product · Server-side feature guide · Live pagination demo · Complete example source
Clone revolist/revogrid-docs, open examples/pivot-workflows, and run:
npm ci
npm run verify:sql
npm run devOpen http://127.0.0.1:49315. The example starts its HTTP endpoint and Vite frontend together. It creates an in-memory database containing synthetic data, so restarting restores the fixture. The documentation website links the source; it does not host this SQL service.
Use Node 24.13 or later. The example installs pinned packages from the public trial registry without an npm token. To use the example in a licensed application, replace the trial dependencies as shown in the installation guide.
The authorized fixture contains seven sales facts. A separate tenant has an additional record worth 9,999; it must affect neither the report nor the available quarter columns.
| Region | 2026-Q1 | 2026-Q2 | Region total |
|---|---|---|---|
| North | 300 | 300 | 600 |
| South | 200 | 400 | 600 |
| West | 50 | 150 | 200 |
| Grand total | 550 | 850 | 1,400 |
With a page size of one, the first page contains North and the second contains South. Both pages must retain 550, 850 and 1,400 in the pinned total row. A total of 600 would mean the application accidentally totaled the current page.
Choose Online in the sales-channel selector. North becomes 500, South 400 and West 50. The whole-report totals become 250 for Q1, 700 for Q2, and 950 overall. Filtering changes the underlying facts; pagination only changes which region is returned.
| Responsibility | Owner |
|---|---|
| Render generated columns and aggregate cells | RevoGrid Pivot |
| Translate page changes into analytical row windows | Pivot with PaginationPlugin |
| Send the Pivot request over HTTP | HttpPivotRemoteStore |
| Authenticate, select the tenant and authorize fields | Application backend |
| Execute SQL, define null semantics and calculate totals | Application backend |
| Return truthful axis counts and a consistent result | Application backend |
The remote API contract is an analytical request format. It is not a database driver and does not make an arbitrary SQL endpoint secure.
The complete client.js registers the grid, imports the styles and adds a request inspector. Its essential configuration is:
import { defineCustomElements } from '@revolist/revogrid/loader';
import { PivotPlugin, HttpPivotRemoteStore } from '@revolist/pivot';
import { PaginationPlugin } from '@revolist/revogrid-pro';
import '@revolist/revogrid-pro/styles.css';
import '@revolist/pivot/styles.css';
defineCustomElements();
const grid = document.querySelector('revo-grid');
const remoteStore = new HttpPivotRemoteStore({ baseUrl: '' });
grid.plugins = [PivotPlugin, PaginationPlugin];
grid.pagination = { itemsPerPage: 1, initialPage: 0, total: 0 };
grid.pivot = {
aggregationSemantics: 'server',
rows: ['region'],
columns: ['quarter'],
filters: ['channel'],
values: [
{ id: 'revenue', prop: 'sales', aggregator: 'sum', label: 'Revenue' },
],
totals: { grandTotal: true },
columnCollapse: false,
contextMenu: false,
engine: {
mode: 'server',
remoteStore,
viewId: 'sales',
fieldsVersion: 'v1',
rowAxis: { offset: 0, limit: 1 },
columnAxis: { offset: 0, limit: 20 },
},
};aggregationSemantics: 'server' records the execution requirement. It does not promise that SQL and local JavaScript aggregators share identical null, count or precision rules.
The starter also supplies a restrictive capability profile: sum over sales, one region row field, and one quarter column field. It disables unsupported authoring actions. Those declarations help the UI; the server still validates every request independently.
Use the direct grid.pagination property. A raw-row pagination loader would bypass the analytical contract. Pivot needs the aggregate row count and generated column paths, not a page of transactions to aggregate locally.
sql-pivot.mjs accepts only the configured view and registry version, the fixed axes, and the revenue measure. It validates offsets and limits, rejects hierarchy expansion, and accepts only known channel values. Requests for another field, an average, a calculation or an aggregate filter fail explicitly.
The SQL table and identifiers are application constants. Filter values are parameters:
const channelPredicate = selected.length
? ` AND channel IN (${selected.map(() => '?').join(', ')})`
: '';
const where = `tenant = ?${channelPredicate}`;
const parameters = [tenantId, ...selected];
const regions = db.prepare(`
SELECT DISTINCT region
FROM sales
WHERE ${where}
ORDER BY region
`).all(...parameters);In the runnable source, tenantId is a separate argument to loadPivot, not a field taken from request JSON. The HTTP demo supplies a fixed synthetic tenant because it has no login. A production route must derive that argument from verified authentication and the user's access rules. Supplying a tenantId property in the request is rejected.
The route also bounds the JSON request to 16 KiB. This makes the example's input surface explicit; production deployments still need their own authentication, request deadlines, database limits and monitoring.
SQL selects the distinct quarters from the same authorized, filtered scope. Each result becomes a column path such as ['2026-Q1']. A requested grand-total column is represented by an empty path with the explicit grandTotal kind.
The response carries both paths and their meanings:
{
"columnAxis": {
"pathEncoding": "semantic-v1",
"paths": [["2026-Q1"], ["2026-Q2"], []],
"kinds": ["leaf", "leaf", "grandTotal"],
"offset": 0,
"limit": 20,
"returned": 3,
"totalCount": 3
}
}Pivot generates headers from this metadata. The browser does not contain a hardcoded list of quarter columns. An inaccessible tenant's 2099-Q9 must never appear in that list.
The row window and column window are independent. Changing the native page controls changes viewport.rowAxis.offset; it does not advance through the quarter axis. A wider report needs a separate application policy for requesting further column windows.
The fixture runs its member reads and aggregate reads in one database transaction. A cell query adds its row and quarter predicates to the authorized source predicate:
SELECT SUM(sales) AS revenue
FROM sales
WHERE tenant = ? AND region = ? AND quarter = ?;The grand-total query deliberately omits the row-page restriction:
SELECT SUM(sales) AS revenue
FROM sales
WHERE tenant = ?;When a channel filter is selected, both queries receive the same additional parameterized channel predicate. Column totals add the quarter predicate but still include every matching region. No total is obtained by adding the visible page's cells.
The response uses data for the requested row groups and summary for the pinned total cells. Each cell has __rowPath, __columnPath, coordinate kinds and the stable measure result ID revenue. Pivot maps those semantic coordinates into generated grid properties.
SQL SUM returns null for an empty group in this example. The backend preserves that value. A business rule that displays a missing combination as zero should be an explicit policy, particularly when adding averages or distinct counts later.
The selector replaces the Pivot configuration with a new member selection:
grid.pivot = {
...pivot,
filterSelections: channel ? { channel: [channel] } : {},
};Pivot sends the selection as a source predicate, and the backend applies it before aggregation. This is different from SQL HAVING, which selects already aggregated groups. The starter rejects having because it does not implement that contract; it never silently ignores it.
For a broader implementation, start with the SQL backend guidance and backend acceptance guidance. Define whether global totals include groups hidden by an aggregate filter, and test that rule separately from ordinary source filters.
Run npm run verify:sql to check the totals across pages, channel filtering, tenant isolation and rejected requests. In the browser, click Next and check that the pinned total stays at 1,400. Then select Online and check that it drops to 950.
This is a bounded integration example, not a warehouse implementation. It supports at most 1,000 row members and 20 quarter members and uses small aggregate queries per requested coordinate. For a large database, replace that strategy with set-based aggregation and database-side member pagination while preserving the same response contract. Benchmark your actual indexes, fact distribution and query plan.
It does not implement hierarchy expansion, subtotals, calculated remote measures, drillthrough, arbitrary sorting, aggregate filters or complete report export. Exporting the currently loaded window is different from exporting every matching group; use the complete server export contract when that is required.
For local calculations, continue with weighted averages, percentages and running totals. For an application that needs analytical output without a grid, see headless Pivot in Node.js.