Skip to content

fix(pivot-table): Correct totals for non-additive metrics - #34592

Closed
rafal-celinski wants to merge 2 commits into
apache:masterfrom
rafal-celinski:master
Closed

rafal-celinski wants to merge 2 commits into
apache:masterfrom
rafal-celinski:master

Conversation

@rafal-celinski

@rafal-celinski rafal-celinski commented Aug 7, 2025 •

Copy link
Copy Markdown

SUMMARY

The previous approach, which relied on a single query with aggregate functions (e.g., SUM, COUNT), has been replaced. The new implementation achieves the same result by executing multiple, separate queries with varying GROUP BY clauses. These results are then merged to construct the final table with all required summary rows in their correct positions.

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

Before:
image

After:
image

TESTING INSTRUCTIONS

  1. Create a Pivot Table chart.
  2. Add one or more dimensions to the Rows (e.g., Genre).
  3. Use a non-additive metric, such as AVG(global_sales).
  4. Enable "Show Column Totals" in the customization options.
  5. Observe the grand total value. It should now be calculated correctly as the average of the entire underlying dataset (e.g., the true AVG(global_sales) across all genres), not as an incorrect sum of averages of the displayed per-genre averages.

ADDITIONAL INFORMATION

  • Has associated issue: Fixes TOTALS incorrect for non-additive metric in pivot table #25747
  • Required feature flags:
  • Changes UI
  • Includes DB Migration (follow approval process in SIP-59)
    • Migration is atomic, supports rollback & is backwards-compatible
    • Confirm DB migration upgrade and downgrade tested
    • Runtime estimates and downtime expectations provided
  • Introduces new feature or API
  • Removes existing feature or API

@dosubot dosubot Bot added the viz:charts:pivot Related to the Pivot Table charts label Aug 7, 2025

@korbit-ai korbit-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Functionality Unsafe reduce on potentially empty array ▹ view 🧠 Not in scope
Design Excessive Function Nesting ▹ view 🧠 Not in standard
Performance Excessive Intermediate Array Creation ▹ view 🧠 Not in standard
Files scanned ​
File Path Reviewed
superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx ✅
superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js ✅

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

Comment on lines +127 to +129
const mainQuery = queriesData.reduce((main_query, query) =>
query.colnames.length > main_query.colnames.length ? query : main_query,
);

This comment was marked as resolved.

Comment on lines +36 to +38
let groupbyCombinations = rows_combinations.flatMap(row =>
cols_combinations.map(col => ({ rows: row, columns: col })),
);

This comment was marked as resolved.

Comment on lines +272 to +287
const cellValue = (formatter = usFmt) =>
function ([attr]) {
return function () {
return {
val: 0,
push(record) {
this.val = record[attr];
},
value() {
return this.val;
},
format: fmtNonString(formatter),
numInputs: typeof attr !== 'undefined' ? 0 : 1,
};
};
};

This comment was marked as resolved.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes the calculation of totals for non-additive metrics (like AVG) in pivot tables. The previous approach incorrectly used aggregation functions on already-aggregated values, leading to incorrect totals. The new implementation executes multiple queries with different GROUP BY clauses and merges results to construct the correct pivot table with accurate summary rows.

  • Replaces single query with multiple queries approach for accurate non-additive metric totals
  • Removes aggregation function selection from UI and simplifies pivot table rendering
  • Updates data structure to support multiple queries with groupby metadata

Reviewed Changes

Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.

Show a summary per file
File Description
utilities.test.ts New test file for buildGroupbyCombinations function
transformProps.test.ts Updated test to reflect new multi-query data structure
buildQuery.test.ts Modified to test multiple query generation
types.ts Added QueryData and Groupby types, removed aggregateFunction
utilities.js Removed aggregation templates and simplified data processing
TableRenderers.jsx Simplified total labels by removing aggregation function references
utilities.ts New utility function to generate groupby combinations
transformProps.ts Updated to handle multiple queries and new data structure
controlPanel.tsx Removed aggregateFunction control and related UI elements
buildQuery.ts Modified to generate multiple queries for different groupby combinations
PivotTableChart.tsx Removed aggregation factory and updated data processing
Comments suppressed due to low confidence (1)

@rusackas

rusackas commented Aug 7, 2025

Copy link
Copy Markdown
Member

There's also a Discussion on related topics #29297

We probably need to look at things like AG Grid to see how they handle this. As long as we have consensus on the change, that'll be great.

@mrobache

Copy link
Copy Markdown

Hi there.
When can this be merged and deployed and in which version ? (6.0.0rc3 ?)

@sadpandajoe sadpandajoe added the 🎪 ⚡ showtime-trigger-start Create new ephemeral environment for this PR label Oct 20, 2025
@ksnikiforov

Copy link
Copy Markdown
Contributor

This is incredible and very needed feature. It would also be nice to have an option to start a pivot table in a collapsed state, and only do the query on expand (as does Power Bi). This would allow to do actual root-cause drill-down into datasets which are much larger than 50k.

@rusackas

rusackas commented Jun 9, 2026

Copy link
Copy Markdown
Member

Thanks @rafal-celinski, this remains a much-wanted fix. Two things before it can land: if you could please rebase (branch is still conflicting), and let's find a way to reach consensus on the multi-query approach I raised (see Discussion #29297 and how AG Grid handles non-additive totals), since firing a query per groupby combination has performance trade-offs. Once we're aligned we'll get it reviewed.

@rusackas

Copy link
Copy Markdown
Member

Converting this to draft whilst it awaits touchups... I think there are a couple similar PRs tackling this. Not sure if @yousoph is still ironing out the kinks on this issue.

@rusackas
rusackas marked this pull request as draft June 16, 2026 17:27
rusackas pushed a commit to rusackas/superset that referenced this pull request Jun 18, 2026
rusackas pushed a commit to rusackas/superset that referenced this pull request Jun 18, 2026
Phase 2 of the non-additive totals SIP (pivot table). Adopt the rollup-level
combination generator from apache#34592 plus its 10 unit tests, and add the Groupby
type. Each combination is a prefix of row dims x prefix of column dims; the
empty combination is the grand total. buildQuery will issue one query per level
so the DB computes each total at its own granularity (multi-query fallback;
GROUPING SETS optimization to follow).

Pure addition (not yet wired into buildQuery/transformProps, which must change
together). SIP.md updated with phase-2 plan + the additivity gate refinement.

Refs apache#25747, apache#32260, apache#36165, apache#29297

Co-Authored-By: Claude Fable 5 <[email protected]>
rusackas pushed a commit to rusackas/superset that referenced this pull request Jun 18, 2026
Make pivot subtotals/grand totals correct for non-additive metrics by computing
each rollup level in the database instead of re-aggregating already-aggregated
cells client-side (adapted from apache#34592, on current TS code).

- buildQuery: emit one query per rollup level (prefix of rows x prefix of cols)
- transformProps: zip each result with its level into QueryData[]; pick the
  longest-colnames result as the detail "mainQuery" for metadata/formatters
- PivotTableChart: tag every record with the level (rows/columns) that produced
  it; drop the client-side aggregatorsFactory
- react-pivottable/PivotData: replace re-aggregation with placement -- a
  `cellValue` passthrough stores the DB-computed value verbatim and processRecord
  drops it into the single matching slot (allTotal/rowTotals/colTotals/tree)
- remove the now-meaningless aggregateFunction control; TableRenderers label
  "Total" instead of "Total (<agg>)"
- update buildQuery/transformProps/tableRenders tests to the new contract;
  60/60 pivot tests pass

Correctness-first: multi-query runs for all metrics (correct for additive too);
the additivity gate + GROUPING SETS single-query are perf optimizations tracked
as phase 3 in SIP.md. Still needs in-app visual verification.

Refs apache#25747, apache#32260, apache#36165, apache#38674, apache#29297

Co-Authored-By: Claude Fable 5 <[email protected]>
@rusackas
rusackas marked this pull request as ready for review June 23, 2026 18:46
@dosubot dosubot Bot added the change:frontend Requires changing the frontend label Jun 23, 2026
@rusackas

Copy link
Copy Markdown
Member

@rafal-celinski this is still a much-wanted fix for #25747. The branch is conflicting, so I'll see if I can help with the rebase to keep it moving, and we'll want to reconcile it against the other pivot-total PRs floating around. Holler if you want to keep driving it.

@bito-code-review

bito-code-review Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Code Review Agent Run #b5a76b

Actionable Suggestions - 0
Additional Suggestions - 6
  • superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/buildQuery.test.ts - 2
    • Removed config field verification · Line 31-31
      The `aggregateFunction: 'Sum'` field was removed from the formData fixture. Verify this field is not consumed by the production `buildQuery` function. If `aggregateFunction` affects query generation downstream, removing it from tests may mask real functionality changes.
    • Semantic duplication in tests · Line 60-128
      Tests 'should build groupby with series in form data' and 'should work with old charts' contain 69-line identical expected arrays, creating maintenance divergence risk. Lines 60-128 and 138-206 are duplicated.
  • superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts - 1
    • E2E test stale reference · Line 60-60
      The Cypress e2e test file (`pivot_table.test.js` line 36) still includes `aggregateFunction: 'Sum'` in the test's formData object. While this won't cause a TypeScript error (it's a JS file), it indicates the test may be relying on a property that was removed from the type definition without considering the e2e impact.
  • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts - 2
    • Redundant variable declarations before swap · Line 25-28
      Lines 25-26 declare `rows` and `columns` as `let`, then lines 28 immediately overwrite them via destructuring. The intermediate declarations are unused. Consider:
      const [rows, columns] = formData.transposePivot
        ? [formData.groupbyColumns, formData.groupbyRows]
        : [formData.groupbyRows, formData.groupbyColumns];

      This eliminates 2 lines of redundant assignment and makes the intent clearer.

      Code suggestion
      --- a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts
      +++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts
       @@ -22,9 +22,8 @@ import { MetricsLayoutEnum, PivotTableQueryFormData } from '../types';
       
        export default function buildGroupbyCombinations(
          formData: PivotTableQueryFormData,
        ) {
      -  let columns = formData.groupbyColumns;
      -  let rows = formData.groupbyRows;
      -
      -  [rows, columns] = formData.transposePivot ? [columns, rows] : [rows, columns];
      +  const [rows, columns] = formData.transposePivot
      +    ? [formData.groupbyColumns, formData.groupbyRows]
      +    : [formData.groupbyRows, formData.groupbyColumns];
       
          const rows_combinations = [[], ...rows.map((_, i) => rows.slice(0, i + 1))];
    • Inconsistent internal constant naming · Line 30-34
      The internal constants use snake_case (`rows_combinations`, `cols_combinations`) while the output variable on line 36 uses camelCase (`groupbyCombinations`). Within the same function, consistent naming improves readability. Consider renaming to `rowsCombinations` and `colsCombinations`.
      Code suggestion
      --- a/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts
      +++ b/superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts
       @@ -27,9 +27,9 @@ export default function buildGroupbyCombinations(
            : [formData.groupbyRows, formData.groupbyColumns];
       
      -  const rows_combinations = [[], ...rows.map((_, i) => rows.slice(0, i + 1))];
      -  const cols_combinations = [
      +  const rowsCombinations = [[], ...rows.map((_, i) => rows.slice(0, i + 1))];
      +  const colsCombinations = [
            [],
            ...columns.map((_, i) => columns.slice(0, i + 1)),
          ];
       @@ -36,5 +36,5 @@ export default function buildGroupbyCombinations(
          let groupbyCombinations = rows_combinations.flatMap(row =>
            cols_combinations.map(col => ({ rows: row, columns: col })),
          );
      -
      +  // becomes rowsCombinations and colsCombinations
  • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts - 1
    • Weak type annotation in utility · Line 33-33
      The `getQueryColumns` parameter uses `any` type (line 33) instead of the properly typed `TimeGranularity | undefined`. While the original inline code used `any`, extracting this into a standalone function is an opportunity to improve type safety and align with the codebase's `TimeGranularity` type from `@superset-ui/core`.
Filtered by Review Rules

Bito filtered these suggestions based on rules created automatically for your feedback. Manage rules.

  • superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts - 1
Review Details
  • Files reviewed - 11 · Commit Range: 1aa713f..17dd515
    • superset-frontend/plugins/plugin-chart-pivot-table/src/PivotTableChart.tsx
    • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/buildQuery.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/controlPanel.tsx
    • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/transformProps.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/src/plugin/utilities.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/TableRenderers.jsx
    • superset-frontend/plugins/plugin-chart-pivot-table/src/react-pivottable/utilities.js
    • superset-frontend/plugins/plugin-chart-pivot-table/src/types.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/buildQuery.test.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/transformProps.test.ts
    • superset-frontend/plugins/plugin-chart-pivot-table/test/plugin/utilities.test.ts
  • Files skipped - 0
  • Tools
    • Whispers (Secret Scanner) - ✔︎ Successful
    • Detect-secrets (Secret Scanner) - ✔︎ Successful
    • Eslint (Linter) - ✔︎ Successful

Bito Usage Guide

Commands

Type the following command in the pull request comment and save the comment.

  • /review - Manually triggers a full AI review.

  • /pause - Pauses automatic reviews on this pull request.

  • /resume - Resumes automatic reviews.

  • /resolve - Marks all Bito-posted review comments as resolved.

  • /abort - Cancels all in-progress reviews.

Refer to the documentation for additional commands.

Configuration

This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].

Documentation & Help

AI Code Review powered by Bito Logo

rusackas pushed a commit to rusackas/superset that referenced this pull request Jun 26, 2026
Fix incorrect totals/subtotals for non-additive metrics (ratios,
COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and
the regular Table chart. Totals are now computed by the database at each
grouping granularity instead of re-aggregating already-aggregated cells.

Pivot Table:
- Emit a single query carrying `grouping_sets` (one rollup level per displayed
  total/subtotal); the database computes every level via native GROUPING SETS
  (gated by a new `supports_grouping_sets` engine capability) or a per-level
  fallback in QueryContextProcessor on engines without support.
- transformProps splits the combined GROUPING SETS result (matched by
  GROUPING() markers) back into per-level data; the react-pivottable aggregator
  becomes a passthrough that places DB-computed values.
- Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a
  single full-detail query is issued and rollup levels are synthesized on the
  client, preserving current behavior/cost.
- Remove the now-meaningless "Aggregation function" control (UPDATING.md).

Table chart:
- Retain post-processing on the show_totals summary query so percent/
  contribution columns are recomputed instead of dropped (apache#37627, apache#34350).

Backend:
- New optional `grouping_sets` query-object field threaded through
  SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the
  chart-data schema; byte-identical query generation when unset.
- New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+
  Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in
  superset/common/grouping_sets.py.

Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite
fallback), additivity detection, table summary path, and the reported-scenario
matrix. Verified in-app on Postgres.

Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426.
Builds on apache#34592. SIP: apache#41463.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@rusackas

Copy link
Copy Markdown
Member

@rafal-celinski first off, thank you for this... it's what got the ball rolling on actually fixing #25747 properly. Your buildGroupbyCombinations (and its tests) got adopted pretty much as-is, and the approach grew from there into a fuller fix covering both the pivot table and the regular table chart, plus a GROUPING SETS path so it's one query instead of N where the engine supports it.

I've written it up as a SIP (#41463) with a working POC in #41184. Rather than have you keep fighting the rebase conflicts here, I think the cleanest path is to carry it forward there and close this one out once that lands, with credit to you. Would love your eyes on either if you have the time. Sound ok?

rusackas pushed a commit to rusackas/superset that referenced this pull request Jul 12, 2026
Fix incorrect totals/subtotals for non-additive metrics (ratios,
COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and
the regular Table chart. Totals are now computed by the database at each
grouping granularity instead of re-aggregating already-aggregated cells.

Pivot Table:
- Emit a single query carrying `grouping_sets` (one rollup level per displayed
  total/subtotal); the database computes every level via native GROUPING SETS
  (gated by a new `supports_grouping_sets` engine capability) or a per-level
  fallback in QueryContextProcessor on engines without support.
- transformProps splits the combined GROUPING SETS result (matched by
  GROUPING() markers) back into per-level data; the react-pivottable aggregator
  becomes a passthrough that places DB-computed values.
- Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a
  single full-detail query is issued and rollup levels are synthesized on the
  client, preserving current behavior/cost.
- Remove the now-meaningless "Aggregation function" control (UPDATING.md).

Table chart:
- Retain post-processing on the show_totals summary query so percent/
  contribution columns are recomputed instead of dropped (apache#37627, apache#34350).

Backend:
- New optional `grouping_sets` query-object field threaded through
  SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the
  chart-data schema; byte-identical query generation when unset.
- New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+
  Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in
  superset/common/grouping_sets.py.

Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite
fallback), additivity detection, table summary path, and the reported-scenario
matrix. Verified in-app on Postgres.

Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426.
Builds on apache#34592. SIP: apache#41463.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@rusackas

Copy link
Copy Markdown
Member

The SIP has passed, and I'm awaiting reviews. I'll close this out in favor of #41184 but if you want to reopen it, or i've overstepped here, just say the word! I'd MORE than welcome your testing/review there, by the way. Can't wait for it to merge.

@rusackas rusackas closed this Jul 17, 2026
@github-actions github-actions Bot removed the 🎪 ⚡ showtime-trigger-start Create new ephemeral environment for this PR label Jul 17, 2026
@rafal-celinski

Copy link
Copy Markdown
Author

Hi! Thanks for the update. To be honest, I haven't had the time to fight the rebase conflicts here lately, so I'm really glad you took the initiative to carry this forward. I'm totally fine with closing this PR in favor of #41184.
​Thanks for the great collaboration, and I really hope to see this merged into master soon!

rusackas pushed a commit to rusackas/superset that referenced this pull request Jul 21, 2026
Fix incorrect totals/subtotals for non-additive metrics (ratios,
COUNT_DISTINCT, AVG, percentiles, percentage metrics) in the Pivot Table and
the regular Table chart. Totals are now computed by the database at each
grouping granularity instead of re-aggregating already-aggregated cells.

Pivot Table:
- Emit a single query carrying `grouping_sets` (one rollup level per displayed
  total/subtotal); the database computes every level via native GROUPING SETS
  (gated by a new `supports_grouping_sets` engine capability) or a per-level
  fallback in QueryContextProcessor on engines without support.
- transformProps splits the combined GROUPING SETS result (matched by
  GROUPING() markers) back into per-level data; the react-pivottable aggregator
  becomes a passthrough that places DB-computed values.
- Additive fast-path: when every metric is additive (SUM/COUNT/MIN/MAX) a
  single full-detail query is issued and rollup levels are synthesized on the
  client, preserving current behavior/cost.
- Remove the now-meaningless "Aggregation function" control (UPDATING.md).

Table chart:
- Retain post-processing on the show_totals summary query so percent/
  contribution columns are recomputed instead of dropped (apache#37627, apache#34350).

Backend:
- New optional `grouping_sets` query-object field threaded through
  SQLA_QUERY_KEYS, QueryObject, QueryObjectDict, get_sqla_query, and the
  chart-data schema; byte-identical query generation when unset.
- New supports_grouping_sets capability (Postgres/BigQuery/Snowflake/Presto+
  Trino); engine-agnostic GROUPING SETS clause/marker/split helpers in
  superset/common/grouping_sets.py.

Tests: rollup synthesis, GROUPING SETS clause/marker/split (native + SQLite
fallback), additivity detection, table summary path, and the reported-scenario
matrix. Verified in-app on Postgres.

Consolidates apache#25747, apache#32260, apache#38674, apache#36165, apache#37627, apache#34350, apache#34425, apache#34426.
Builds on apache#34592. SIP: apache#41463.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

change:frontend Requires changing the frontend plugins size/XXL viz:charts:pivot Related to the Pivot Table charts

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TOTALS incorrect for non-additive metric in pivot table

6 participants