Pivot Table in Excel: Step-by-Step Tutorial

By Dr. Zubair Khalid, DVM, MS, PhD ·

Pivot Table in Excel: Step-by-Step Tutorial

By the end of this tutorial you will be able to take a flat research table, insert a PivotTable, drag fields into the Rows, Columns, Values and Filters areas, switch an aggregation from Count to Sum or Average, and add a calculated field. You will also know how to spot the four mistakes that break most pivot tables built from lab and field data.

You need Microsoft Excel for Windows or Mac (any version from 2013 onward works, and the steps are nearly identical in Microsoft 365) and one clean dataset. Everything below uses a single worked example of 40 animals with four columns: Species, Group, Sex and BodyWeight_kg. The whole dataset is small enough to type by hand in about ten minutes, and it is realistic enough to expose every common error.

Pivot tables are not a niche skill. They appear in the methods sections of published research across very different fields. A seven-year measles surveillance analysis in Ethiopia was run in Microsoft Excel and Pivot software [1]. A bibliometric study of tuberculosis detection used Pivot Tables for its performance analysis [2], and a mapping of bipolar disorder and digital psychiatry research used Excel Pivot Tables for descriptive statistics on 4,753 articles [3]. A pharmacovigilance review of 789 herbal product reports used pivot tables for analysis and presentation [4], and a national dementia prevalence study in the Republic of Korea drew on age-sex pivot table records from the National Health Insurance Service [5]. The tool is the same whether you are counting adverse events or weighing mice.

What a PivotTable Actually Does

Flexmonster pivot table with rows, columns, and chart view
A pivot table summarizes rows and columns of data, much like the animal dataset used in this tutorial. Image: Flexmonster, CC BY-SA 4.0, via Wikimedia Commons.

A PivotTable is a summary engine. It reads a source range, groups the rows by the values in one or more columns, and then calculates something for each group. The source data never changes. The pivot table is a separate object that sits on its own worksheet and recalculates whenever you refresh it.

The word "pivot" describes the act of rotating your view of the data. The same 40 rows can be summarized by species, by group, by sex, or by any combination, without you writing a single formula. In compositional data analysis, the related term "pivot" refers to a coordinate transformation used to move data into a space where standard statistics behave properly [6]. Excel's PivotTable is a different idea with a shared name: it rotates the axes of a summary, not the geometry of a dataset.

Two rules govern everything that follows.

First, the source must be a flat table. One header row, one record per row, no blank rows, no blank columns, no merged cells, no subtotal rows buried in the middle. A merged cell is the single fastest way to produce a pivot table that silently drops records.

Second, every column needs a unique, non-empty header. Excel uses the header text as the field name in the PivotTable Field List. Two columns both called "Weight" become "Weight" and "Weight2", and you will never remember which is which.

The Worked Dataset: 40 Animals

Type or paste this into a new worksheet starting at cell A1. Keep it on a sheet named RawData. Do not add formatting, colors or blank spacer rows.

AnimalIDSpeciesGroupSexBodyWeight_kg
A01MouseControlM24.1
A02MouseControlF21.3
A03MouseControlM25.0
A04MouseControlF22.7
A05MouseControlM23.8
A06MouseControlF20.9
A07MouseControlM24.6
A08MouseControlF21.8
A09MouseTreatmentM27.4
A10MouseTreatmentF24.9
A11MouseTreatmentM28.1
A12MouseTreatmentF25.6
A13MouseTreatmentM26.8
A14MouseTreatmentF24.2
A15MouseTreatmentM27.9
A16MouseTreatmentF25.1
A17RatControlM312.5
A18RatControlF268.4
A19RatControlM325.1
A20RatControlF274.9
A21RatControlM318.7
A22RatControlF271.2
A23RatControlM309.8
A24RatControlF266.5
A25RatTreatmentM341.2
A26RatTreatmentF289.7
A27RatTreatmentM352.6
A28RatTreatmentF296.3
A29RatTreatmentM347.9
A30RatTreatmentF291.4
A31RatTreatmentM338.5
A32RatTreatmentF287.1
A33ZebrafishControlM0.62
A34ZebrafishControlF0.81
A35ZebrafishControlM0.58
A36ZebrafishControlF0.77
A37ZebrafishTreatmentM0.71
A38ZebrafishTreatmentF0.94
A39ZebrafishTreatmentM0.68
A40ZebrafishTreatmentF0.89

You now have 40 rows and 5 columns, with 40 unique AnimalIDs. Before you build anything, confirm the shape: click any cell inside the block and press Ctrl+A (Command+A on Mac). Excel selects the whole contiguous region. The Name Box in the top-left corner should read 5R x 5C or similar, meaning 5 rows by 5 columns of headers plus data. If the selection stops short, you have a blank cell inside the block. Find it and fix it now.

Step 1: Convert the Range to a Real Table (Optional but Recommended)

This step is optional. It is also the single best protection against a stale source range.

  1. Click any cell inside your data.
  2. Go to Insert, then Table. Excel guesses the range. Confirm that "My table has headers" is checked.
  3. Click OK.

Excel applies a banded style and adds filter arrows to the header row. The Name Box now shows a table name such as Table1. You can rename it in the Table Design tab, for example to tblAnimals.

The benefit appears later. When you add row 41, the table expands automatically, and any pivot table built on the table name picks up the new row on refresh. A pivot table built on a fixed range like $A$1:$E$41 does not.

If you prefer to skip this step, that is fine. Just remember the range you selected, because you will need to update it manually when new data arrives.

Step 2: Insert the PivotTable

  1. Click any single cell inside the data or the table.
  2. Go to the Insert tab on the ribbon and click PivotTable. On Windows the button sits at the far left of the Insert tab. On Mac it is in the same place.
  3. Excel opens the Create PivotTable dialog. Under "Choose the data that you want to analyze", select "Select a table or range" if you skipped Step 1, or "From Table/Range" if you made a table.
  4. The Table/Range box shows something like RawData!$A$1:$E$41 or tblAnimals.
  5. Under "Choose where you want the PivotTable to be placed", pick "New Worksheet". This keeps the summary separate from the raw records, which matters when you later share the file.
  6. Click OK.

Excel creates a new sheet with an empty pivot frame on the left and the PivotTable Fields pane on the right. The pane lists your five fields as checkboxes: AnimalID, Species, Group, Sex, BodyWeight_kg.

The bottom of the pane shows four drop zones, which Excel calls areas:

  • Filters: fields placed here become report-level filters above the pivot table.
  • Columns: fields placed here become column labels across the top.
  • Rows: fields placed here become row labels down the left side.
  • Values: fields placed here are summarized with a calculation.

That is the whole interface. Everything else is dragging.

Step 3: Drag Fields into the Four Areas

Start with the most common research question: what is the mean body weight for each species in each treatment group?

  1. Drag Species from the field list into the Rows area.
  2. Drag Group into the Columns area.
  3. Drag BodyWeight_kg into the Values area.

The pivot table now shows three row labels (Mouse, Rat, Zebrafish) and three column labels (Control, Treatment, Grand Total), with numbers in the cells. The default calculation Excel chose is almost certainly Sum, not Average, because the field contains numeric values. You will fix that in the next step.

Add a filter so you can look at one sex at a time:

  1. Drag Sex into the Filters area.

A filter dropdown now appears above the pivot table with "(All)" selected. Choosing "F" restricts every number in the table to females without changing the layout.

The field list shows checkmarks next to Species, Group, Sex and BodyWeight_kg, confirming each is in use.

What each area does, in one table

FieldAreaAggregationResult
SpeciesRowsNone (label)Three row labels: Mouse, Rat, Zebrafish
GroupColumnsNone (label)Three column labels: Control, Treatment, Grand Total
SexFiltersNone (filter)Dropdown above the table, default (All)
BodyWeight_kgValuesSum by default, switch to AverageMean body weight in kilograms per species-group cell
AnimalIDValues (optional)CountNumber of animals per cell, used as an n-check

That last row is worth adopting as a habit. Drag AnimalID into the Values area as a second value field. Excel counts it because it is text. Now every cell shows both a mean and an n. If a cell shows an n of 4, you know the mean rests on four animals. If it shows 1, something is wrong with your grouping.

Step 4: Change Sum to Average

  1. In the Values area at the bottom of the field list, click the small arrow next to "Sum of BodyWeight_kg".
  2. Choose "Value Field Settings".
  3. In the "Summarize values by" tab, select Average.
  4. Click OK.

The header changes from "Sum of BodyWeight_kg" to "Average of BodyWeight_kg", and every number drops by roughly a factor of four, because each cell now averages four animals instead of adding them.

For the Mouse Control males, the four weights are 24.1, 25.0, 23.8 and 24.6 kg, so the average is 24.375 kg. Excel displays 24.38 if the cell is formatted to two decimals. Right-click any value cell, choose Number Format, and set two decimal places for a cleaner report.

The same Value Field Settings dialog offers Count, Count Numbers, Max, Min, Product, StdDev, StdDevp, Var and Varp. For research summaries, Average, Count, StdDev and Var are the ones you will use most. Note that StdDev in a pivot table is the sample standard deviation, which is what you want for a group of animals.

Step 5: Add a Calculated Field

Suppose you want body weight expressed as a percentage of the overall mean for that species. A calculated field does this without touching the source data.

  1. Click anywhere inside the pivot table so the PivotTable Analyze tab appears on the ribbon. On older versions the tab is called Options.
  2. Click Fields, Items & Sets, then Calculated Field.
  3. In the Name box, type PctOfSpeciesMean.
  4. In the Formula box, clear what is there and type:
= BodyWeight_kg / 100

That formula is deliberately trivial. A more useful one divides each animal's weight by a constant you have stored elsewhere, or multiplies two existing fields. If your source table had a column for feed intake in grams, you could write:

= BodyWeight_kg / FeedIntake_g
  1. Click Add, then OK.

The new field appears in the field list and can be dragged into the Values area like any other.

Two limits apply. A calculated field operates on the sum of each field, not on individual rows, so a ratio of two fields is computed from the totals in each cell, not from each animal's ratio averaged afterward. And a calculated field cannot reference a cell, a range or another pivot table. If you need row-level arithmetic, add a helper column to the source data instead. That is the more transparent choice for publication anyway, because a reviewer can see the formula in the sheet.

Step 6: Refresh, Sort and Format

When the underlying data changes, the pivot table does not update on its own. Right-click anywhere in the pivot table and choose Refresh, or press Alt+F5 on Windows. On Mac, use the Refresh button on the PivotTable Analyze tab.

Sorting is done from the row or column label dropdown. Click the arrow next to "Row Labels" and choose Sort A to Z, Sort Z to A, or More Sort Options for a sort by value. Sorting Rat above Mouse, for example, is a value sort on the Average column, largest to smallest.

For a report-ready table, right-click a value cell, choose Number Format, and set the category to Number with two decimals. Then go to PivotTable Design, Report Layout, and choose "Show in Tabular Form" if you want a plain grid rather than the compact indented layout. Tabular form is easier to copy into a manuscript table.

Common Mistakes and Limitations

Four errors account for most broken pivot tables in research settings. Each has a specific symptom and a specific fix.

Numbers stored as text

Symptom: the Values area shows Count instead of Sum, or the sum is 0, or the value field settings offer no numeric options.

Cause: the cells look like numbers but Excel treats them as text. This happens constantly when data are pasted from a web page, exported from a laboratory instrument, or typed with a stray leading apostrophe. A text number is left-aligned by default, while a true number is right-aligned, though cell formatting can override that visual cue.

Diagnosis: click a suspicious cell and look at the status bar at the bottom of the window. If it shows only a count and no sum or average, the cell is text. You can also use =ISNUMBER(A2) in an empty cell. It returns TRUE for a real number and FALSE for text.

Fix: select the column, go to Data, Text to Columns, click Finish without changing any settings. Excel re-parses each value. Alternatively, multiply the column by 1 in a helper column with =A2*1 and paste the results back as values. After the fix, refresh the pivot table.

Duplicate or blank headers

Symptom: the field list shows "Weight" and "Weight2", or a column appears as "Column1".

Cause: two header cells contain the same text, or a header cell is empty.

Fix: rename every column so each header is unique and descriptive. Use BodyWeight_kg rather than Weight, and DateOfBirth rather than DOB, especially if you will merge files later. Then refresh. Excel keeps the old field names in the pivot table until you refresh, and orphaned fields remain in the list until you remove them.

Stale source range

Symptom: you added rows 41 to 60, refreshed, and the new animals do not appear in the totals. Or the pivot table's source range still reads $A$1:$E$41.

Cause: the pivot table was built on a fixed range and the range did not grow.

Fix: click inside the pivot table, go to PivotTable Analyze, Change Data Source, and either extend the range or point it at a table name. The permanent fix is to convert the source to a table before inserting the pivot table, as in Step 1. Then the range grows with the data and refresh is enough.

Count versus Sum defaulting

Symptom: a column of body weights shows a count of 4 in each cell instead of a mean of 24.38.

Cause: Excel defaults to Count when the field contains any text or blank, and to Sum when every value is numeric. A single blank cell in a weight column flips the whole field to Count.

Fix: use Value Field Settings to set the aggregation explicitly, and check the source column for blanks. In the worked dataset, every weight cell is populated, so the default is Sum, which is still the wrong answer for this question. Always set the aggregation on purpose.

Other limits worth knowing

A pivot table cannot show text values in the Values area. Dragging Species into Values gives you a count of species, not a list of names. Use a formula such as TEXTJOIN or a filtered copy of the source if you need to display labels.

Pivot tables do not update when you edit a source cell until you refresh. In a shared workbook, two people can look at the same file and see different numbers for this reason.

A calculated field cannot reference individual rows, so ratios and normalized values are usually better computed as helper columns in the source table.

Finally, pivot tables summarize. They do not test. A mean of 24.38 kg in one cell and 25.65 kg in the next is a description, not evidence. The dementia prevalence study cited above was explicitly descriptive and applied no inferential tests [5], and the golf injury analysis used pivot tables for trends while computing incidence rate ratios separately [7]. Follow that pattern: use the pivot table to see the shape of the data, then run the statistics in a tool built for it.

A Quick Sanity Check on Any Pivot Table

Before you trust a number, run three checks.

First, compare the grand total to the raw data. Sum the BodyWeight_kg column in the source sheet with =SUM(RawData!E2:E41). The pivot table's grand total should match exactly. In the worked dataset the sum is 4,417.41 kg. If your pivot grand total differs, records are being dropped or double-counted.

Second, check the n. With AnimalID in Values as a Count, every cell should show 4, and the grand total should show 40. Any other number means a grouping problem.

Third, spot-check one cell by hand. Mouse, Control, Male should average 24.1, 25.0, 23.8 and 24.6, which is 24.375. If the pivot table says 24.38, the aggregation is correct.

Converting a Pivot Table Back to a Flat Table

Sometimes you need the summary as ordinary cells you can sort, chart or export. This is the "pivot to table" move.

  1. Select the entire pivot table, including headers.
  2. Copy with Ctrl+C.
  3. Right-click a cell on a new sheet, choose Paste Special, then Values.
  4. The result is a static block of numbers with no pivot machinery attached.

Use this when you are handing data to a collaborator who does not need to refresh anything, or when you are pasting a summary table into a manuscript. The trade-off is real: the pasted copy no longer updates. Keep the live pivot table on its own sheet so you can regenerate the static copy whenever the data change.

If you need the reverse direction, turning a cross-tab back into one row per observation, that is a different operation. Excel does not do it natively in the PivotTable interface. The standard approach is to copy the cross-tab, paste it with values, and then use a formula or a manual reshape. In R, the same idea is handled by pivot functions, and one package for Drosophila and C. elegans survival analysis includes a pivot_prism function that converts "one row, multiple individuals" data into a "one row, one individual" layout for plotting survival curves [8]. The concept is identical: reshape between wide and long.

Frequently Asked Questions

How do I pivot a table in Excel?

Click any cell in your flat data, go to Insert, click PivotTable, confirm the range, and choose New Worksheet. Then drag fields from the PivotTable Fields pane into the Rows, Columns, Values and Filters areas.

Why does my pivot table show Count instead of Sum?

Excel defaults to Count when the field contains text, blanks or numbers stored as text. Check the source column with =ISNUMBER() and convert text numbers using Data, Text to Columns, then set the aggregation manually in Value Field Settings.

How do I change Sum to Average in a pivot table?

Click the arrow next to the value field name in the Values area, choose Value Field Settings, select Average under "Summarize values by", and click OK. The header changes to "Average of" followed by the field name.

Why are my new rows missing from the pivot table?

The pivot table is probably built on a fixed range that did not grow. Use Change Data Source to extend the range, or convert the source to an Excel Table first so the range expands automatically, then refresh.

Can a pivot table use a column with duplicate headers?

No. Excel renames the second column to something like "Weight2" and you lose track of which is which. Rename every header so it is unique before you insert the pivot table.

What is a calculated field in a pivot table?

A calculated field is a new field you define with a formula that uses existing fields, such as = BodyWeight_kg / FeedIntake_g. Add it from PivotTable Analyze, then Fields, Items & Sets, then Calculated Field.

How do I turn a pivot table back into a normal table?

Select the pivot table, copy it, then paste with Paste Special, Values onto a new sheet. You get static numbers that no longer refresh, which is useful for sharing or for pasting into a manuscript.

Does a pivot table update automatically when I edit the source data?

No. You must refresh it manually with Alt+F5 on Windows or the Refresh button on the PivotTable Analyze tab. Automatic refresh on file open is a separate setting in PivotTable Options.

Where Pivot Tables Fit in a Research Workflow

A pivot table is a first-pass summarizer. It answers questions like "how many animals per group", "what is the mean weight by sex", and "which district reported the most cases" in seconds, without formulas. That speed is why the tool shows up in published work across surveillance, bibliometrics and clinical audits. A 10-year hand trauma analysis used pivot tables to break down age, sex, case-mix index and revenue [9]. A study of pork and feed ingredient imports from African swine fever affected countries organized five years of trade data into pivot tables for description [10]. An acupuncture literature review built pivot tables for acupoint frequency and meridian attribution across 311 articles [11].

The pattern is consistent. Pivot tables handle description. Statistical testing happens elsewhere. A meta-analysis of exercise therapy for chronic ankle instability extracted data into an Excel spreadsheet and then ran the pooled analysis in dedicated software [12]. A scoping review of prostate cancer in Nigeria charted data in Excel and used Stata for meta-analysis [13]. A systematic review of mindfulness and burnout collected data in Excel, analyzed it in pivot tables, and presented the results in graphs and maps [14]. A multi-center homeopathy study in India used pivot tables for demographics, morbidity and prescription frequency across 2,811 patients [15]. An endotoxin safety analysis used descriptive statistics and pivot tables across three FDA data sources spanning 2008 to 2021 [16].

What all of these have in common is a clean source table and a clear question. The pivot table does not decide what to compare. You do. Build the summary, check the n, verify the grand total against the raw column, and then take the numbers into the analysis that fits your design.

For a 40-animal dataset, that whole cycle takes about fifteen minutes. The same workflow scales to thousands of rows, which is why it is worth learning properly on a small example first.

Related Articles

Sources

  1. Epidemiology of Measles in Bale Zone, Southeast Ethiopia: Analysis of Surveillance Data from 2013 to 2019.
  2. Private sector engagement in tuberculosis detection: a bibliometric analysis.
  3. Mapping scientific trends in bipolar disorder and digital psychiatry (2000-2025): A bibliometric and visualized analysis of AI-driven diagnosis and digital interventions.
  4. Analysis of Reports on Adverse Drug Reactions Related to Herbal Medicinal Products and Herbal Supplements in the Netherlands Received by the National Pharmacovigilance Centre Lareb.
  5. National Surveillance-Based Retrospective Longitudinal Analysis of Dementia Prevalence Trends in the Republic of Korea, 2016-2025, with a One-Year 2026 Forecast Using National Health Insurance Service Administrative Data.
  6. Relating starter cultures to volatile profile and potential markers in green Spanish-style table olives by compositional data analysis.
  7. Epidemiology of Golf-Related Injuries: A 10-Year Analysis of the National Electronic Injury Surveillance System Database and the Impact of Alcohol Consumption.
  8. ggbulksurv: An R package for easy Drosophila and C. elegans survival analysis.
  9. [[10 years of hand traumatology - an epidemiological, structural and economic analysis at a maximum care provider].](https://pubmed.ncbi.nlm.nih.gov/33588487/)
  10. An analysis of select swine feed ingredients and pork products imported into the United States from African swine fever virus affected countries.
  11. [[Clinical application characteristics of acupuncture and moxibustion in treatment of cervicogenic headache based on complex network analysis].](https://pubmed.ncbi.nlm.nih.gov/41116994/)
  12. Exercise Therapy for Chronic Ankle Instability: Which Modality for Which Deficit? A Systematic Review and Meta-Analysis.
  13. Prostate cancer in Nigeria: a scoping review and meta-analysis of current evidence on process indicators and interventions.
  14. Effects of standardized mindfulness programs on burnout: a systematic review and original analysis from randomized controlled trials.
  15. The Patient Population at Homeopathic Outpatient Clinics across India: A Clinical Data Collection Study.
  16. A Nontrivial Analysis of Patient Safety Risk from Parenteral Drug- and Medical Device-Borne Endotoxin.