How to Pivotby Function in Excel

Learn multiple Excel methods to pivot data dynamically with the new PIVOTBY function. Step-by-step examples, business use cases, and advanced tips included.

excelformulaspreadsheettutorial
12 min read • Last updated: 7/2/2025

How to Pivotby Function in Excel

Why This Task Matters in Excel

The ability to summarise and reshape raw data into meaningful cross-tab reports is one of the skills that separates casual spreadsheet users from true data analysts. Traditionally, Excel users relied on classic PivotTables for this task. While powerful, PivotTables live in their own object layer, require refreshing, and cannot be embedded inside larger formulas. When you build automated dashboards, schedule data refreshes, or need the results to spill into other calculations without manual intervention, a formula-based solution is preferable.

The new dynamic-array function PIVOTBY (available to Microsoft 365 Insiders at the time of writing and rolling out to regular channels later) delivers a game-changing alternative. It generates a live, spill-range pivot table directly on the worksheet, combining the best aspects of PivotTables and functions such as SUMIFS or the “old school” CSE techniques.

Consider a sales analyst who receives transactional data every morning. Management expects an updated margin by product category versus region before the first team meeting. With traditional PivotTables, the analyst must:

  1. Drop in the new rows,
  2. Refresh the PivotTable,
  3. Possibly adjust the layout, and
  4. Ensure downstream formulas reference the correct pivot cache.

With PIVOTBY, the analyst simply pastes the new rows under the existing list; the function recalculates instantly, and every dependent chart or KPI box updates.

Industry scenarios abound: finance teams performing month-end variance analysis, logistics departments summarising shipments by warehouse and carrier, marketing groups evaluating campaign performance across segments, or educators tracking student scores by class and assessment. In each case, PIVOTBY brings:

  • Dynamic updates without refresh buttons,
  • Seamless references inside other formulas (no GETPIVOTDATA required),
  • Full compatibility with other dynamic array functions for cascading analysis, and
  • A familiar layout resembling classical pivot tables yet controlled entirely via formula logic.

Failing to master PIVOTBY keeps analysts tethered to manual refresh cycles, makes workbooks more brittle, and prevents lightweight models from scaling as data grows. By adding this skill, you unlock an end-to-end, formula-native data pipeline that connects with tools such as Power Query, Power BI, and Excel-based reporting frameworks.

Best Excel Approach

The most effective way to create dynamic, formula-based cross-tabs is to leverage PIVOTBY in combination with good data hygiene (clean headers, formatted Excel tables, and unpivoted source data). While functions like SUMIFS, UNIQUE, or even SEQUENCE+FILTER can replicate some pivot behaviour, they require more scaffolding and often multiple helper formulas. PIVOTBY encapsulates all those steps in a single function call and automatically spills the entire two-dimensional result. Use this method when:

  • You need a compact, one-cell solution that updates automatically.
  • The pivot must feed additional formulas without manual references.
  • You want to avoid the overhead of a PivotTable object or cache.

Prerequisites: Office 365 build 2404 or later, data stored in a proper Excel Table (recommended but not mandatory), and column headers with no duplicates.

Conceptually, PIVOTBY groups by chosen row fields, splits columns by one field, aggregates a value field, and optionally adds totals. The core syntax looks like this:

=PIVOTBY(data, rows, columns, values, aggregation, include_totals, sort)

Parameter explanations:

  • data – The entire transactional table or range including headers.
  • rows – One or more columns to group on the vertical axis.
  • columns – A single column to pivot across the horizontal axis.
  • values – The numeric column to aggregate (sum, count, average, etc.).
  • aggregation – A text instruction such as \"SUM\", \"COUNT\", \"AVERAGE\", \"MAX\", \"MIN\".
  • include_totals – Optional TRUE or FALSE (defaults to TRUE) to control grand totals.
  • sort – Optional \"ASC\", \"DESC\", or omitted for default order.

Alternative approaches include:

=LET(uRows,UNIQUE(Table1[Category]), uCols,UNIQUE(Table1[Region]), 
     SUMIFS(Table1[Sales],Table1[Category],uRows,Table1[Region],TRANSPOSE(uCols)))

or

=PIVOTBY(Table1, [Category], [Region], [Sales], "COUNT")

The LET+UNIQUE+SUMIFS pattern works even in older 365 builds but is longer, more error-prone, and harder to maintain.

Parameters and Inputs

  • data: Provide the entire source including header labels. Using an Excel Table (Insert ➜ Table) lets you refer to columns by structured names like Table1[Sales], and ensures the range auto-expands when new rows arrive. A standard range like [A1:E1000] also works but does not grow.
  • rows: Accepts a single column or an array of several columns inside a CHOOSECOLS wrapper. Data types can be text, numbers, or dates. Missing values will appear as blank labels.
  • columns: Only one field is permitted in the current preview build. It determines the column labels of the resulting pivot.
  • values: Must be a numeric field if you plan to perform math aggregations. Non-numeric content can still be used for \"COUNT\" or \"COUNTA\".
  • aggregation: Case-insensitive text. \"SUM\" is default if omitted. Unsupported strings return a #CALC! error.
  • include_totals: Optional Boolean. Set to FALSE to suppress grand totals in both directions.
  • sort: Controls row sort order. Use \"ASC\", \"DESC\", or a custom array of ranks.

Data preparation: remove trailing spaces, align data types, and avoid merged cells inside the list. If the column chosen for columns contains more than 255 unique items, the spill range may exceed sheet boundaries, so consider filtering first. Empty columns or duplicate header names cause #VALUE! errors.

Step-by-Step Examples

Example 1: Basic Scenario – Sales by Region

Imagine a simple table named SalesData with the following columns: Date, Rep, Region, Product, Units, Revenue. For this first example you want a quick snapshot of total revenue by region.

  1. Place the cursor in any empty cell, ideally on a separate “Summary” sheet to keep raw data and summaries apart.
  2. Enter:
=PIVOTBY(SalesData, , [Region], [Revenue], "SUM", FALSE)

Notice that rows is omitted, so PIVOTBY treats the result as a one-row, multi-column summary. Because include_totals is FALSE, you get a horizontal list of regional totals without a trailing grand total.

Expected result:

(blank)EastNorthSouthWest
Revenue128,50097,400110,250135,000

Why it works: PIVOTBY scans the Region column, finds the distinct labels [East, North, South, West], then computes SUM of Revenue for each label. With no row field specified, the entire dataset sits on one aggregated row.

Variations:

  • Replace \"SUM\" with \"COUNT\" to count orders.
  • Set include_totals to TRUE to display an extra total column.
  • Use a spill-referenced chart by selecting the top-left cell and inserting a column chart; the chart expands automatically when new regions appear.

Troubleshooting tips: If you see #SPILL!, ensure the cells to the right have no content or formatting. If #CALC! appears, verify the Revenue column is numeric.

Example 2: Real-World Application – Margin by Product Category and Quarter

Your finance department tracks margins and needs a matrix that shows average margin percentage for each product category across fiscal quarters. The source table Financials has: OrderID, Category, Quarter, MarginPct.

Step-by-step:

  1. Confirm Quarter values are consistent (Q1, Q2, Q3, Q4). Any typos like “Qtr1” will create separate columns.
  2. Create a blank sheet named “Dashboards”.
  3. In cell B2, enter:
=PIVOTBY(Financials, [Category], [Quarter], [MarginPct], "AVERAGE", TRUE, "ASC")
  1. Format the spill range as Percentage with 1 decimal place.
  2. Insert conditional formatting: Data Bars ➜ Gradient fill to visualise high and low margins. Because PIVOTBY spills, the conditional format range auto-extends when new categories arrive.
  3. Add a slicer to the source table for Year (if present). Changing the slicer filters the underlying data and instantly recalculates the PIVOTBY result.

Business value: senior managers now have a live view of profit quality across categories and time, linked to slicers for interactive exploration without any VBA or pivot refresh macros.

Integration:

  • You can nest the spill reference inside another formula:
=IF(Dashboard!B3:B10>0.35,"Excellent","Review")
  • Use XLOOKUP against the top row of the pivot to pull a specific quarter’s average into a KPI card elsewhere.

Performance considerations: With 50,000 rows, calculations remain almost instantaneous because PIVOTBY leverages the same in-memory engine as modern PivotTables. However, adding numerous slicers or volatile functions like INDIRECT might slow recalculation.

Example 3: Advanced Technique – Multi-Level Rows, Custom Ranking, and Error Handling

Scenario: An operations analyst wants to summarise on-time delivery rate by Warehouse and Carrier, with the carriers across columns sorted by performance (best to worst). Data table named Logistics has: Date, Warehouse, Carrier, OnTimeFlag (1 for on time, 0 late).

  1. Create a helper column OnTimePct using:
=AVERAGEIFS(Logistics[OnTimeFlag], Logistics[Carrier], [@Carrier], Logistics[Warehouse], [@Warehouse])

Alternatively, aggregate on the fly inside PIVOTBY.

  1. In a cell on the “OpsSummary” sheet, build a custom carrier order:
=LET(rates, PIVOTBY(Logistics,,[Carrier],[OnTimeFlag],"AVERAGE",FALSE),
     carrierNames, INDEX(rates,1,SEQUENCE(,COLUMNS(rates))),
     sorted, SORTBY(carrierNames, INDEX(rates,2,SEQUENCE(,COLUMNS(rates))), -1))
  1. Feed the result into CHOOSECOLS inside PIVOTBY to force custom column order:
=PIVOTBY(Logistics, CHOOSECOLS(Logistics, {"Warehouse"}), sorted, [OnTimeFlag], "AVERAGE")
  1. Trap potential divide-by-zero errors where a warehouse-carrier combination has no records:
=IFERROR(previous_formula, "n/a")
  1. Apply number format Percentage, two decimals. Use conditional formatting icon sets: green check for rates above 95 percent, yellow minus for 90-95 percent, red exclamation below 90 percent.

Why advanced: This example chains LET, SORTBY, INDEX, SEQUENCE, and CHOOSECOLS to manipulate the PIVOTBY result, producing a performance-based ranking that updates automatically as new data flows in. Handling missing combinations prevents #DIV/0! clutter.

Professional tips: Consider storing the helper formulas in hidden rows to keep the model readable. Document each LET variable inside comments; future maintainers will thank you.

Tips and Best Practices

  1. Convert source ranges to Excel Tables to ensure dynamic expansion and clearer structured references.
  2. Keep column headers short and unique; the pivot labels inherit them. Avoid special characters that could break downstream formulas or Power BI connections.
  3. Use LET to break complicated PIVOTBY setups into named steps. This improves readability and performance since intermediate results are calculated only once.
  4. Combine PIVOTBY with TAKE or DROP to remove totals or limit the result to a top-N list for dashboards.
  5. When sharing workbooks with colleagues on older Excel builds, wrap the function inside IFERROR with a friendly message advising them to upgrade.
  6. Always check spill range boundaries; large column counts can crash into the sheet edge. Place PIVOTBY near cell A1 or use XLOOKUP to retrieve pieces of the spill if space is tight.

Common Mistakes to Avoid

  1. Forgetting to use tables: Relying on fixed ranges means new rows are ignored. Convert to a table or adjust the range argument.
  2. Duplicated headers: Two columns both named “Sales” confuse PIVOTBY and produce #VALUE!. Rename headings clearly.
  3. Using non-numeric columns as the Values field with math aggregations: If you aggregate “SUM” on a text field, you receive a #CALC! error. Switch to “COUNT” or convert data types.
  4. Blocking the spill area: Hidden formatting, comments, or merged cells can prevent the array from expanding, leading to #SPILL!. Clear the space to the right and below.
  5. Ignoring case sensitivity on aggregation text: While the argument is technically case-insensitive, accidental leading spaces (“ SUM”) trigger errors. Trim input or hard-code the text.

Alternative Methods

MethodProsConsBest forCompatible with older Excel
PIVOTBYOne-cell formula, auto spill, integrates with dynamic arraysRequires latest Microsoft 365 buildModern automated modelsNo
Classic PivotTablePowerful UI, field list, slicersSeparate object, manual refresh, not part of formula flowInteractive ad-hoc analysisYes (all versions)
SUMIFS + UNIQUE + TRANSPOSEWorks in any 365 build, granular controlMultiple helper ranges, harder to maintainCustom layouts prior to PIVOTBY availabilityPartially (needs dynamic arrays)
Power Pivot (Data Model)Handles millions of rows, uses DAXLearning curve, add-in overheadEnterprise scale reportingYes (Excel 2010+)
GETPIVOTDATA referencing a PivotTableStable references, backward compatibilityBreaks when layout changes, verbose formulasPulling a few key measuresYes

When deciding, weigh user audience, Excel version, dataset size, and need for automation. Migrating from SUMIFS to PIVOTBY is as simple as replacing the spill formula, assuming the underlying data is tidy. Moving from a PivotTable requires re-creating row, column, and value selections in PIVOTBY and adjusting any GETPIVOTDATA links.

FAQ

When should I use this approach?

Use PIVOTBY whenever you need a dynamic cross-tab that recalculates instantly without manual refresh, feeds other formulas, or simplifies complex SUMIFS scaffolding. Reporting dashboards, scheduled refresh models, and template workbooks benefit the most.

Can this work across multiple sheets?

Yes. Reference the data argument with a full sheet scope, for example: =PIVOTBY('Data Sheet'!A1:G5000, …). If the list is an official table, you can call it from any sheet: =PIVOTBY(SalesData, …). The spill result lives on the sheet where you enter the formula.

What are the limitations?

Current preview builds restrict the columns parameter to one field. Calculated items, grouped dates, and custom subtotals found in classic PivotTables are not yet available. The spill range cannot exceed the sheet’s 16,384-column limit, so extremely wide pivots may need filtering or separate sections.

How do I handle errors?

Wrap PIVOTBY inside IFERROR to catch data type mismatches or invalid aggregation labels:

=IFERROR(PIVOTBY(Table1,…),"Check data integrity")

Investigate #VALUE! for header issues, #SPILL! for blocked ranges, and #CALC! for unsupported operations.

Does this work in older Excel versions?

No. PIVOTBY requires the dynamic array engine introduced in Office 365 and is currently limited to Insider builds. For Excel 2019 or earlier, rely on PivotTables or the SUMIFS+UNIQUE combination.

What about performance with large datasets?

PIVOTBY leverages the same optimised calculation engine as modern PivotTables. It handles tens of thousands of rows gracefully. For hundreds of thousands, consider loading the data into Power Pivot or Power Query first, then reference the cleaned table with PIVOTBY. Avoid volatile functions and maintain proper column data types to keep recalc times low.

Conclusion

Mastering the PIVOTBY function elevates your Excel toolbox by merging the automation of formulas with the analytic power of PivotTables. You can create live, embeddable cross-tabs that refresh instantly, integrate seamlessly with charts and downstream calculations, and eliminate manual refresh cycles. Add this skill to your repertoire, keep your data tidy, and explore related dynamic array functions to build truly modern, self-updating workbooks. Your future dashboards—and your stakeholders—will thank you.

We use tracking cookies to understand how you use the product and help us improve it. Please accept cookies to help us improve.