Power Query course · Lesson 17 of 17
Project: a self-updating monthly sales report
Build a complete monthly sales report: combine a folder of exports, clean them, add product data and targets, check for gaps and refresh with one click.
This final lesson puts the whole course to work. You will build the kind of workbook that saves a sales analyst a day every month: monthly ERP exports dropped into a folder are combined, cleaned, enriched with product costs, compared with regional targets and summarised in a report that refreshes with one click. Every technique comes from an earlier lesson, and each step links back to it so you can revise as you go.
The brief
- Source data: the ERP writes one CSV per month,
sales_2026-01.csv,sales_2026-02.csvand so on, into a shared folder. Columns:OrderID,OrderDate,Region,Rep,SKU,Qty,UnitPrice,Status. - Product master: an Excel table
tblProductsin the report workbook withSKU,Product,CategoryandUnitCost, maintained by purchasing. - Targets: an Excel table
tblTargetswith one row per region and one column per month (JantoDec), maintained by the sales director. - Output: a summary per month and region with revenue, margin, number of orders, target and percentage of target; plus a clean detail table in the Data Model for PivotTables.
- Routine: next month, save the new CSV in the folder and click Data › Refresh All. Nothing else.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | OrderID | OrderDate | Region | SKU | Qty | UnitPrice |
| 2 | SO-9001 | 2026-01-05 | north | rtr-x2 | 4 | 99.00 |
| 3 | SO-9002 | 2026-01-05 | North | SW-8P | 10 | 59.00 |
| 4 | SO-9003 | 2026-01-06 | SOUTH | AP-300 | 2 | 145.00 |
| 5 | SO-9004 | 2026-01-07 | South | RTR-X2 | 1 | 99.00 |
Before: the first rows of sales_2026-01.csv (Rep and Status columns not shown). Inconsistent case and spaces, and everything is text.
Step 1: the settings sheet
Add a sheet Settings with two input cells, as in Parameters and custom functions. Put the folder path in B2 and name the cell pFolder (type the name in the Name Box). Put the report year 2026 in B3 and name it pYear. Then create a blank query (Data › Get Data › From Other Sources › Blank Query), open Home › Advanced Editor, paste the code below and name the query Settings.
let
Get = (cellName as text) => Excel.CurrentWorkbook(){[Name = cellName]}[Content]{0}[Column1]
in
[Folder = Get("pFolder"), Year = Get("pYear")]Step 2: the product master
Click inside tblProducts and choose Data › From Table/Range. Name the query Products and make the key clean and unique, because a duplicate SKU would multiply sales rows in the merge (Merge queries: every join kind explained).
let
Source = Excel.CurrentWorkbook(){[Name = "tblProducts"]}[Content],
Typed = Table.TransformColumnTypes(Source, {{"SKU", type text}, {"Product", type text}, {"Category", type text}, {"UnitCost", type number}}),
CleanKey = Table.TransformColumns(Typed, {{"SKU", each Text.Upper(Text.Trim(_)), type text}}),
UniqueKey = Table.Distinct(CleanKey, {"SKU"})
in
UniqueKeyStep 3: the sales query
Create another blank query named Sales and paste the code. It reads the folder (as in Combine files from a folder, but in a compact hand-written form), cleans the text (Cleaning text and numbers in Power Query), removes cancelled orders (Filtering, sorting and removing rows and columns), adds a month column (Dates, durations and a calendar table), merges product data and calculates revenue and margin (Custom and conditional columns).
let
Source = Folder.Files(Settings[Folder]),
CsvOnly = Table.SelectRows(Source, each Text.Lower([Extension]) = ".csv" and Text.StartsWith(Text.Lower([Name]), "sales_")),
Parsed = Table.AddColumn(CsvOnly, "Data", each Table.PromoteHeaders(
Csv.Document([Content], [Delimiter = ",", Encoding = 65001, QuoteStyle = QuoteStyle.Csv]),
[PromoteAllScalars = true])),
Kept = Table.SelectColumns(Parsed, {"Name", "Data"}),
Expanded = Table.ExpandTableColumn(Kept, "Data", {"OrderID", "OrderDate", "Region", "Rep", "SKU", "Qty", "UnitPrice", "Status"}),
Typed = Table.TransformColumnTypes(Expanded, {{"OrderDate", type date}, {"Qty", Int64.Type}, {"UnitPrice", type number}}, "en-US"),
Cleaned = Table.TransformColumns(Typed, {
{"Region", each Text.Proper(Text.Trim(_)), type text},
{"Rep", Text.Trim, type text},
{"SKU", each Text.Upper(Text.Trim(_)), type text},
{"Status", Text.Trim, type text}}),
NotCancelled = Table.SelectRows(Cleaned, each [Status] <> "Cancelled"),
ThisYear = Table.SelectRows(NotCancelled, each Date.Year([OrderDate]) = Settings[Year]),
AddMonth = Table.AddColumn(ThisYear, "Month", each Date.StartOfMonth([OrderDate]), type date),
Merged = Table.NestedJoin(AddMonth, {"SKU"}, Products, {"SKU"}, "P", JoinKind.LeftOuter),
WithProduct = Table.ExpandTableColumn(Merged, "P", {"Product", "Category", "UnitCost"}),
AddRevenue = Table.AddColumn(WithProduct, "Revenue", each [Qty] * [UnitPrice], type number),
AddMargin = Table.AddColumn(AddRevenue, "Margin", each if [UnitCost] = null then null else [Qty] * ([UnitPrice] - [UnitCost]), type number),
Final = Table.RemoveColumns(AddMargin, {"Name", "Status"})
in
Final| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | OrderID | Month | Region | SKU | Revenue | Margin |
| 2 | SO-9001 | 2026-01-01 | North | RTR-X2 | 396 | 152 |
| 3 | SO-9002 | 2026-01-01 | North | SW-8P | 590 | 250 |
| 4 | SO-9003 | 2026-01-01 | South | AP-300 | 290 | 114 |
| 5 | SO-9004 | 2026-01-01 | South | RTR-X2 | 99 | 38 |
After: the first four of several hundred January order lines, now clean, typed and enriched (some columns hidden). Unit costs are 61 for RTR-X2, 34 for SW-8P and 88 for AP-300.
Step 4: a data quality check
A margin of null means an SKU is missing from the product master. Do not let that hide in a total. Create a query Check_UnknownSKUs with a Left Anti join and load it to a small table on the report sheet, where an empty table means all is well.
let
Anti = Table.NestedJoin(Sales, {"SKU"}, Products, {"SKU"}, "P", JoinKind.LeftAnti),
SkuList = Table.Distinct(Table.SelectColumns(Anti, {"SKU", "Month"}))
in
SkuListStep 5: targets from a cross-tab
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Region | Jan | Feb | Mar |
| 2 | North | 45000 | 47000 | 50000 |
| 3 | South | 42000 | 44000 | 46000 |
Before: tblTargets, as the sales director likes to type it (April to December not shown).
Unpivot it as in Unpivot and pivot: reshaping tables and turn the month names into real dates, so they match the Month column of Sales:
let
Source = Excel.CurrentWorkbook(){[Name = "tblTargets"]}[Content],
Unpivoted = Table.UnpivotOtherColumns(Source, {"Region"}, "MonthName", "Target"),
AddMonth = Table.AddColumn(Unpivoted, "Month", each
Date.FromText("1 " & [MonthName] & " " & Text.From(Settings[Year]), [Culture = "en-GB"]), type date),
Typed = Table.TransformColumnTypes(AddMonth, {{"Region", type text}, {"Target", type number}}),
Result = Table.SelectColumns(Typed, {"Region", "Month", "Target"})
in
Result| A | B | C | |
|---|---|---|---|
| 1 | Region | Month | Target |
| 2 | North | 2026-01-01 | 45000 |
| 3 | North | 2026-02-01 | 47000 |
| 4 | North | 2026-03-01 | 50000 |
| 5 | South | 2026-01-01 | 42000 |
| 6 | South | 2026-02-01 | 44000 |
| 7 | South | 2026-03-01 | 46000 |
After: Targets ready to merge on Region and Month.
Step 6: the summary
Group the detail by month and region (Group By: totals, counts and the All Rows trick), then merge the targets on two keys and calculate the percentage. The result below assumes the folder holds the complete January and February exports, several hundred order lines each, so its totals are sums over all those lines rather than over the few sample rows shown earlier.
let
Grouped = Table.Group(Sales, {"Month", "Region"}, {
{"Revenue", each List.Sum([Revenue]), type number},
{"Margin", each List.Sum([Margin]), type number},
{"Orders", each List.Count(List.Distinct([OrderID])), Int64.Type}}),
Joined = Table.NestedJoin(Grouped, {"Month", "Region"}, Targets, {"Month", "Region"}, "T", JoinKind.LeftOuter),
WithTarget = Table.ExpandTableColumn(Joined, "T", {"Target"}),
AddPct = Table.AddColumn(WithTarget, "% of target", each if [Target] = null or [Target] = 0 then null else [Revenue] / [Target], Percentage.Type),
Sorted = Table.Sort(AddPct, {{"Month", Order.Ascending}, {"Region", Order.Ascending}})
in
Sorted| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Month | Region | Revenue | Margin | Target | % of target |
| 2 | 2026-01-01 | North | 48200 | 17350 | 45000 | 107.1% |
| 3 | 2026-01-01 | South | 39650 | 13880 | 42000 | 94.4% |
| 4 | 2026-02-01 | North | 51300 | 18470 | 47000 | 109.1% |
| 5 | 2026-02-01 | South | 44100 | 15210 | 44000 | 100.2% |
After, with the full January and February files loaded (every order line, not just the four sample rows shown above): the finished summary, Orders column hidden. March appears automatically when sales_2026-03.csv lands in the folder.
Step 7: loading
Decide where each query goes, as discussed in Performance, query folding and refresh options. Right-click each query in Data › Queries & Connections and choose Load To…:
| Query | Load to | Why |
|---|---|---|
| Settings | Only Create Connection | Helper |
| Products | Only Create Connection (+ Data Model if you want product slicers) | Lookup |
| Targets | Only Create Connection | Lookup |
| Sales | Only Create Connection + Add this data to the Data Model | Large detail for PivotTables |
| Summary | Table on the Report sheet | The report people read |
| Check_UnknownSKUs | Table on the Report sheet | Quality control |
Optionally add the calendar query from Dates, durations and a calendar table to the Data Model, relate it to Sales[OrderDate], and build PivotTables and slicers on top (PivotCharts, slicers and timelines). Format the Summary table with a percentage format on % of target and conditional formatting that turns values below 100% red.
tblSummary). Formulas such as XLOOKUP or SUMIFS that point at tblSummary[Revenue] keep working after every refresh, however many rows the table gets.Step 8: the monthly routine and a test run
- Save
sales_2026-03.csvinto the folder. Do not rename columns or open and re-save it in Excel (Excel may change the date format). - Open the report and choose Data › Refresh All (
Ctrl+Alt+F5). - Check
Check_UnknownSKUs: it should be empty. - Check the row count in Queries & Connections: Sales should have grown by roughly one month of lines.
- Compare the March total in the Summary with the ERP's own total for March. A matching total is the best proof the recipe is right.
To test the robustness before relying on it, try these deliberate accidents on a copy: put a readme.txt in the folder (it is ignored by the extension filter), add an unknown SKU to a CSV (it shows up in the check table), change pYear to 2025 (the report empties because there is no 2025 data), and rename the Qty header in one file (the rows from that file get null quantity and the revenue drops; a good reason to compare totals every month).
Ideas to extend the project
- Add a
Returnedstatus handling: keep returns with negative quantity instead of removing them. - Read the targets for several years by adding a
Yearcolumn totblTargetsand merging on three keys. - Replace the local folder path with a SharePoint folder so colleagues can refresh in Excel for the web.
- Turn the cleaning steps of Sales into a function
fnCleanSalesand reuse it for a second ERP that exports the same layout. - Add a rolling 12-month filter with
Date.IsInPreviousNMonthsinstead of the fixed year.
/Users/…). In Excel for the web the workbook refreshes only if the folder is a SharePoint or OneDrive folder accessed with From SharePoint Folder.Check yourself
1. Why are SKU values uppercased and trimmed in both Sales and Products?
rtr-x2 and RTR-X2 would not match otherwise.
2. What does the Check_UnknownSKUs query use?
Left Anti returns sales rows whose SKU has no match in Products.
3. Why count Orders with List.Distinct([OrderID]) instead of Count Rows?
Count Rows would count order lines, not orders.
4. Where should the large Sales detail be loaded?
The Data Model handles large detail tables for PivotTables.
5. A refresh fails with Formula.Firewall. What is the first thing to check?
The Sales query combines several sources, which the privacy firewall controls.