Try it on four order lines
Someone sends a purchasing spreadsheet back. Which order is new? Did the quantity change? Did a line disappear? Open the practice workbook, compare your output with the four expected rows, or go straight to the Power Query M template. If an order number repeats, the template pairs rows in their order within that number. Use a stable line number as part of the key when the row order might change.
A month-end question a lookup can't settle
The version I sent out and the version I got back look almost alike. A VLOOKUP can find the first occurrence of a number. It can't tell me which of two lines with that number disappeared. Conditional formatting makes the differences colorful and leaves me doing the detective work again next month. I wanted a refreshable report that names the row, the field and the old and new values. That same comparison is useful when the columns hold a budget, cost or audit record instead of a purchase order.
What counts as a change?
Match both sides on the key and, for repeated keys, the occurrence within the group. A row found on one side only is Added or Removed. A matched pair is Unchanged if the comparable non-key fields agree and Modified if one differs. For a quantity change, 수량_Diff will show 10 → 15. Equal prices and names leave their difference cells blank. A line number is safer than occurrence order when the source can be resorted.
Run the query on a real workbook
What you should see
Open the XLSX practice file. Its before and after sheets contain the two named tables below. In the same workbook create a blank query, paste the M code in Advanced Editor and choose Close & Load. The practice guide sheet gives you a result to check against.
The copy sent out, P06_Start
| Order Number | Product Name | Quantity | Amount |
|---|---|---|---|
| PO-001 | Valve A | 10 | 100,000 |
| PO-002 | Valve B | 5 | 50,000 |
| PO-002 | Valve C | 3 | 30,000 |
The copy returned, P06_Ending
| Order Number | Product Name | Quantity | Amount |
|---|---|---|---|
| PO-001 | Valve A | 15 | 150,000 |
| PO-002 | Valve B | 5 | 50,000 |
| PO-003 | Valve D | 7 | 70,000 |
The four rows the query should return
| Order Number | Product Name | ChangeType | Quantity_Diff | Amount_Diff |
|---|---|---|---|---|
| PO-001 | Valve A | Modified | 10 → 15 | 100000 → 150000 |
| PO-002 | Valve B | Unchanged | null | null |
| PO-002 | Valve C | Removed | null | null |
| PO-003 | Valve D | Added | null | null |
The display combines the keys for readability. In the actual Added row for Valve D you'll find the new number in 발주번호_End and the new name in 제품명_End. The before-side fields are empty.
The M template
The query reads Excel table names, which can differ from the names on the sheet tabs. Name the source tables first. The comments and field identifiers in the examples match the downloadable workbook. Microsoft's Excel.CurrentWorkbook reference
let
//--------------------------------------------------
// 1. Set the two table names and the matching keys.
//--------------------------------------------------
StartName = "P06_Start", // 과거 테이블명
EndName = "P06_Ending", // 현재 테이블명
KeyCols = {"발주번호"}, // 키 열 (복합키는 {"A","B"})
Culture = "ko-KR", // 지역 설정
//--------------------------------------------------
// 2. Load the source tables from this workbook.
//--------------------------------------------------
S0 = Excel.CurrentWorkbook(){[Name = StartName]}[Content],
E0 = Excel.CurrentWorkbook(){[Name = EndName ]}[Content],
//--------------------------------------------------
// 3. Number repeated occurrences within each key.
//--------------------------------------------------
fnAddDupIdx = (tbl as table) as table =>
let
Numbered = Table.AddIndexColumn(tbl, "__SourceOrder", 0, 1, Int64.Type),
Groups = Table.Group(Numbered, KeyCols, {{
"Rows", each Table.AddIndexColumn(
Table.Sort(_, {{"__SourceOrder", Order.Ascending}}),
"__DupIndex", 1, 1, Int64.Type
)
}}),
Columns = Table.ColumnNames(tbl) & {"__DupIndex"}
in Table.Combine(Groups[Rows], Columns),
S = fnAddDupIdx(S0),
E = fnAddDupIdx(E0),
NonKeyCols = List.Difference(
List.Union({Table.ColumnNames(S0), Table.ColumnNames(E0)}), KeyCols
),
//--------------------------------------------------
// ④ Full Outer Join
//--------------------------------------------------
JoinKeys = List.Combine({KeyCols, {"__DupIndex"}}),
Join = Table.NestedJoin(
S, JoinKeys,
E, JoinKeys,
"EndRec",
JoinKind.FullOuter
),
X = Table.ExpandTableColumn(
Join, "EndRec",
Table.ColumnNames(E),
List.Transform(Table.ColumnNames(E), each _ & "_End")
),
//--------------------------------------------------
// An unmatched row has an occurrence number on only one side.
// For a matched row, collect the original fields whose values differ.
//--------------------------------------------------
AddDiffCols = Table.AddColumn(
X, "ChangedCols",
(r) =>
if r[__DupIndex] = null or r[__DupIndex_End] = null then null
else
let
changed = List.Select(NonKeyCols, (c) =>
not Value.Equals(
Record.FieldOrDefault(r, c, null),
Record.FieldOrDefault(r, c & "_End", null)
)
)
in if List.IsEmpty(changed) then null else changed
),
AddStatus = Table.AddColumn(
AddDiffCols, "ChangeType", each
if [__DupIndex] = null then "Added"
else if [__DupIndex_End] = null then "Removed"
else if [ChangedCols] = null then "Unchanged"
else "Modified",
type text
),
Result = List.Accumulate(
NonKeyCols, AddStatus,
(state, col) =>
Table.AddColumn(
state, col & "_Diff",
each
let
hasChanged = ([ChangedCols] <> null) and
List.Contains([ChangedCols], col),
oldVal = Record.FieldOrDefault(_, col, null),
newVal = Record.FieldOrDefault(_, col & "_End", null),
oldTxt = if oldVal = null then "" else Text.From(oldVal, Culture),
newTxt = if newVal = null then "" else Text.From(newVal, Culture)
in
if hasChanged then oldTxt & " → " & newTxt
else null,
type text
)
)
in
Result
Put the same join to work in accounting
Once the join is reliable, the interesting question becomes what a difference means. Here are four different answers from an accounting desk.
First case. Did we spend what we budgeted?
Why the comparison matters
At every close someone matches accounts and departments by hand, calculates variances, and flags the items a manager needs to explain. This is how a missed row or a percentage against the wrong denominator ends up in a slide.
Give the budget and ledger a common key
Approved budget, Budget_2025
| Account Code | Department | Budget Amount | Remarks |
|---|---|---|---|
| Salaries | Sales | 50,000,000 | Monthly |
| Salaries | Administration | 30,000,000 | Monthly |
| Staff welfare | Sales | 5,000,000 | |
| Staff welfare | Administration | 3,000,000 | |
| Training | Administration | 2,000,000 |
Actual spend, Actual_2025
| Account Code | Department | Actual spend | Remarks |
|---|---|---|---|
| Salaries | Sales | 52,000,000 | More overtime |
| Salaries | Administration | 29,500,000 | One employee left |
| Staff welfare | Sales | 5,200,000 | |
| Staff welfare | Administration | 2,500,000 | Event cancelled |
| Marketing expenses | Sales | 10,000,000 | New item |
Join on account and department
let
// 1. Choose the tables.
StartName = "Budget_2025",
EndName = "Actual_2025",
// 2. Use both fields as the composite key.
KeyCols = {"계정과목", "부서"},
// 3. Continue with the original comparison query.
Culture = "ko-KR",
// ... continue with the base template
in
Result
Read the matched and unmatched lines
| Account Code | Department | ChangeType | Budget Amount | Actual spend | Budget_Diff | Actual_Diff | ChangedCols |
|---|---|---|---|---|---|---|---|
| Salaries | Sales | Modified | 50,000,000 | 52,000,000 | null | null | ["Actual Amount","Remarks"] |
| Salaries | Administration | Modified | 30,000,000 | 29,500,000 | null | null | ["Actual Amount","Remarks"] |
| Staff welfare | Sales | Modified | 5,000,000 | 5,200,000 | null | null | ["Actual Amount"] |
| Staff welfare | Administration | Modified | 3,000,000 | 2,500,000 | null | null | ["Actual Amount","Remarks"] |
| Training | Administration | Removed | 2,000,000 | null | null | null | null |
| Marketing expenses | Sales | Added | null | 10,000,000 | null | null | null |
Calculate a useful variance
Subtract budget from actual. Calculate a percentage only when there is a meaningful budget denominator. An unbudgeted charge needs its own flag, however ordinary the department's total might look.
// Add the following analysis columns to Result.
// 1. Calculate the amount over or under budget.
AddVariance = Table.AddColumn(
Result, "차이액",
each
if [ChangeType] = "Modified" then
[실적금액_End] - [예산금액]
else if [ChangeType] = "Added" then
[실적금액_End]
else if [ChangeType] = "Removed" then
-[예산금액]
else null,
type number
),
// 2. Express the variance as a percentage.
AddVarianceRate = Table.AddColumn(
AddVariance, "차이율(%)",
each
if [ChangeType] = "Modified" and [예산금액] <> 0 then
Number.Round(([실적금액_End] - [예산금액]) / [예산금액] * 100, 1)
else null,
type number
),
// 3. Flag absolute variances of at least ten percent.
AddFlag = Table.AddColumn(
AddVarianceRate, "주의필요",
each
if [차이율(%)] <> null and Number.Abs([차이율(%)]) >= 10 then
"⚠️ 중요"
else null,
type text
)
Put amount, percentage and exception together
| Account Code | Department | ChangeType | Budget Amount | Actual spend | Variance | Variance (%) | Review flag |
|---|---|---|---|---|---|---|---|
| Salaries | Sales | Modified | 50,000,000 | 52,000,000 | +2,000,000 | +4.0 | null |
| Salaries | Administration | Modified | 30,000,000 | 29,500,000 | -500,000 | -1.7 | null |
| Staff welfare | Sales | Modified | 5,000,000 | 5,200,000 | +200,000 | +4.0 | null |
| Staff welfare | Administration | Modified | 3,000,000 | 2,500,000 | -500,000 | -16.7 | ⚠️ Important |
| Training | Administration | Removed | 2,000,000 | null | -2,000,000 | null | null |
| Marketing expenses | Sales | Added | null | 10,000,000 | +10,000,000 | null | null |
A view for the person who owns the budget
Group by department in a PivotTable. Put budget, actual spend, net variance and budget utilization side by side.
| Department | Total Budget | Actual spend | Variance | Budget utilization (%) |
|---|---|---|---|---|
| Sales | 55,000,000 | 67,200,000 | +12,200,000 | 122.2 |
| Administration | 35,000,000 | 32,000,000 | -3,000,000 | 91.4 |
Then open the exceptions. Admin's staff welfare expense fell 16.7 percent when an event was cancelled. Sales booked ₩10 million of marketing without a budget line. Those two cases need very different conversations.
Second case. Is the sales change seasonal?
The business question
Which product is growing, in which region? A product that first appears this month shouldn't be reported as if it had an ordinary percentage increase. The same goes for a line that disappeared.
Two monthly extracts
September sales, Sales_202409
| Product Code | Region | Sales Amount | Units sold |
|---|---|---|---|
| PROD-A | Seoul | 100,000,000 | 1,000 |
| PROD-A | Busan | 50,000,000 | 500 |
| PROD-B | Seoul | 80,000,000 | 800 |
| PROD-B | Busan | 40,000,000 | 400 |
| PROD-C | Seoul | 30,000,000 | 300 |
October sales, Sales_202410
| Product Code | Region | Sales Amount | Units sold |
|---|---|---|---|
| PROD-A | Seoul | 120,000,000 | 1,200 |
| PROD-A | Busan | 45,000,000 | 450 |
| PROD-B | Seoul | 85,000,000 | 850 |
| PROD-B | Busan | 42,000,000 | 420 |
| PROD-D | Seoul | 50,000,000 | 500 |
Match each product within its region
let
// Compare consecutive months.
StartName = "Sales_202409", // 9월 (과거)
EndName = "Sales_202410", // 10월 (현재)
KeyCols = {"제품코드", "지역"},
Culture = "ko-KR",
// ... use the base comparison
in
Result
Calculate growth where a base exists
// Sales growth
AddSalesGrowth = Table.AddColumn(
Result, "매출성장률(%)",
each
if [ChangeType] = "Modified" and [매출액] <> 0 then
Number.Round(([매출액_End] - [매출액]) / [매출액] * 100, 1)
else if [ChangeType] = "Added" then
null // 신규는 성장률 계산 불가
else null,
type number
),
// Volume growth
AddQtyGrowth = Table.AddColumn(
AddSalesGrowth, "판매량성장률(%)",
each
if [ChangeType] = "Modified" and [판매량] <> 0 then
Number.Round(([판매량_End] - [판매량]) / [판매량] * 100, 1)
else null,
type number
),
// Assign a trend label.
AddTrend = Table.AddColumn(
AddQtyGrowth, "트렌드",
each
if [ChangeType] = "Added" then "🆕 신규"
else if [ChangeType] = "Removed" then "❌ 중단"
else if [매출성장률(%)] >= 10 then "📈 고성장"
else if [매출성장률(%)] >= 0 then "➡️ 안정"
else if [매출성장률(%)] >= -10 then "📉 주의"
else "🚨 급감"
,
type text
)
Read the October result
| Product Code | Region | ChangeType | September Sales | October Sales | Sales Growth Rate (%) | Units sold Growth Rate (%) | Trend |
|---|---|---|---|---|---|---|---|
| PROD-A | Seoul | Modified | 100,000,000 | 120,000,000 | +20.0 | +20.0 | 📈 High growth |
| PROD-A | Busan | Modified | 50,000,000 | 45,000,000 | -10.0 | -10.0 | 📉 Caution |
| PROD-B | Seoul | Modified | 80,000,000 | 85,000,000 | +6.3 | +6.3 | ➡️ Stable |
| PROD-B | Busan | Modified | 40,000,000 | 42,000,000 | +5.0 | +5.0 | ➡️ Stable |
| PROD-C | Seoul | Removed | 30,000,000 | null | null | null | ❌ Discontinued |
| PROD-D | Seoul | Added | null | 50,000,000 | null | null | 🆕 New |
Make the same comparison year over year
// Compare the same period a year apart.
StartName = "Sales_202310", // 2023년 10월
EndName = "Sales_202410", // 2024년 10월
KeyCols = {"제품코드", "지역"},
Keep the product-and-region key. Switch the earlier input to the same month last year to look past a seasonal swing.
Third case. Where did the cost variance come from?
The manufacturing question
A unit of output costs more than the standard. Did we pay more for material, use a different quantity, or see labor or overhead move? Start by keeping standard and actual measures in separate columns.
Two views of the same product
The standard, StandardCost
| Product Code | Material Cost (Standard) | Labor Cost (Standard) | Manufacturing Overhead (Standard) | Standard Quantity | Standard Rate |
|---|---|---|---|---|---|
| PROD-001 | 1,000 | 500 | 200 | 100 | 1,700 |
| PROD-002 | 2,000 | 800 | 300 | 50 | 3,100 |
| PROD-003 | 1,500 | 600 | 250 | 80 | 2,350 |
What production recorded, ActualCost
| Product Code | Material Cost (Actual) | Labor Cost (Actual) | Manufacturing Overhead (Actual) | Actual Quantity | Actual Unit Price |
|---|---|---|---|---|---|
| PROD-001 | 1,200 | 480 | 220 | 110 | 1,900 |
| PROD-002 | 1,950 | 820 | 310 | 48 | 3,080 |
| PROD-003 | 1,600 | 650 | 270 | 85 | 2,520 |
Match by product code
let
StartName = "StandardCost",
EndName = "ActualCost",
KeyCols = {"제품코드"},
Culture = "ko-KR",
// ... use the base comparison
in
Result
Separate price effects from quantity effects
Hold the standard price fixed when isolating a quantity change. Use actual quantity when measuring the difference between actual and standard prices. Check the units carefully before interpreting a component variance alongside a per-unit total.
// 1. Isolate the material quantity variance.
AddMQV = Table.AddColumn(
Result, "재료비_수량차이",
each
if [ChangeType] = "Modified" then
([실제수량_End] - [표준수량]) * [표준단가]
else null,
type number
),
// 2. Isolate the material price variance.
AddMPV = Table.AddColumn(
AddMQV, "재료비_가격차이",
each
if [ChangeType] = "Modified" then
([실제단가_End] - [표준단가]) * [실제수량_End]
else null,
type number
),
// 3. Compare the displayed unit costs.
AddTotalVar = Table.AddColumn(
AddMPV, "총원가차이",
each
if [ChangeType] = "Modified" then
([재료비(실제)_End] + [노무비(실제)_End] + [제조경비(실제)_End]) -
([재료비(표준)] + [노무비(표준)] + [제조경비(표준)])
else null,
type number
),
// 4. Label the variance.
AddVarType = Table.AddColumn(
AddTotalVar, "차이유형",
each
if [총원가차이] = null then null
else if [총원가차이] > 0 then "🔴 불리한 차이"
else if [총원가차이] < 0 then "🟢 유리한 차이"
else "⚪ 차이 없음",
type text
)
Read the cost report
| Product Code | ChangeType | Standard Cost | Actual Cost | Material Cost_Quantity Variance | Material Cost_Price Variance | Total Cost Variance | Variance Type |
|---|---|---|---|---|---|---|---|
| PROD-001 | Modified | 1,700 | 1,900 | +170 | +2,200 | +200 | 🔴 Unfavorable Variance |
| PROD-002 | Modified | 3,100 | 3,080 | -310 | -96 | -20 | 🟢 Favorable Variance |
| PROD-003 | Modified | 2,350 | 2,520 | +235 | +425 | +170 | 🔴 Unfavorable Variance |
Two products worth investigating
PROD-001 shows a 200 increase in the displayed unit cost. Output was 110 against a standard quantity of 100. The example separately flags +170 for the material quantity measure and +2,200 for the price measure, a reason to look at purchasing terms. PROD-002's unit cost falls by 20 and quantity is 48 against 50, with material indicators of −310 and −96. These columns use different bases. They aren't a set of amounts to add to the reported unit-cost change.
Fourth case. What happened to the asset register?
The audit question
A change in an inventory quantity, financial statement balance or asset record needs a trail back to evidence. A before-and-after comparison can identify which transaction warrants an explanation.
The register at two points in the close
Opening register, FixedAssets_Before
| Asset Number | Asset Name | Acquisition Cost | Accumulated Depreciation | Book Value | Department |
|---|---|---|---|---|---|
| FA-001 | Server Equipment | 10,000,000 | 6,000,000 | 4,000,000 | IT |
| FA-002 | Vehicle | 30,000,000 | 15,000,000 | 15,000,000 | Sales |
| FA-003 | Office Equipment | 5,000,000 | 3,000,000 | 2,000,000 | Administration |
Closing register, FixedAssets_After
| Asset Number | Asset Name | Acquisition Cost | Accumulated Depreciation | Book Value | Department |
|---|---|---|---|---|---|
| FA-001 | Server Equipment | 10,000,000 | 6,200,000 | 3,800,000 | IT |
| FA-002 | Vehicle | 30,000,000 | 15,500,000 | 14,500,000 | Sales |
| FA-004 | Multifunction printer | 3,000,000 | 0 | 3,000,000 | Administration |
Match on asset number
let
StartName = "FixedAssets_Before",
EndName = "FixedAssets_After",
KeyCols = {"자산번호"},
Culture = "ko-KR",
// ... use the base comparison
// Add the review timestamp and reviewer.
AddAuditMeta = Table.AddColumn(
Result, "검증일시",
each DateTime.LocalNow(),
type datetime
),
AddUser = Table.AddColumn(
AddAuditMeta, "검증자",
each Environment.UserName,
type text
),
// Classify the change for review.
AddSeverity = Table.AddColumn(
AddUser, "중요도",
each
if [ChangeType] = "Added" then "🆕 신규 취득"
else if [ChangeType] = "Removed" then "⚠️ 폐기/매각"
else if [ChangedCols] <> null and
List.Contains([ChangedCols], "취득가액") then
"🚨 취득가액 수정"
else if [ChangedCols] <> null and
List.Contains([ChangedCols], "감가상각누계액") then
"📝 정상 감가상각"
else "ℹ️ 기타 변경",
type text
)
in
AddSeverity
An exception list with a timestamp
| Asset Number | Asset Name | ChangeType | ChangedCols | Importance | Reviewed at | Reviewer |
|---|---|---|---|---|---|---|
| FA-001 | Server Equipment | Modified | ["Accumulated Depreciation","Book Value"] | 📝 Normal Depreciation | 2025-10-04 15:30 | bjt |
| FA-002 | Vehicle | Modified | ["Accumulated Depreciation","Book Value"] | 📝 Normal Depreciation | 2025-10-04 15:30 | bjt |
| FA-003 | Office Equipment | Removed | null | ⚠️ Disposal/Sale | 2025-10-04 15:30 | bjt |
| FA-004 | Multifunction printer | Added | null | 🆕 New Acquisition | 2025-10-04 15:30 | bjt |
Use the list to find the evidence
FA-003 disappeared. Match it to the disposal approval and the evidence of removal. FA-004 appeared. Locate the acquisition record and the time it was checked. Routine depreciation should change accumulated depreciation and book value. A change to historical acquisition cost is a different matter and deserves a prominent flag. Filter those cases into the review report. The comparison identifies the exceptions. The records explain them.
// Show only changes that need review.
Table.SelectRows(
AddSeverity,
each [중요도] = "🚨 취득가액 수정" or
[중요도] = "⚠️ 폐기/매각" or
[중요도] = "🆕 신규 취득"
)
Before adapting the template
Four checks I make on a new dataset
Examine duplicates and null keys, then compare the underlying types of numeric fields. Decide whether a single key identifies a row or a composite key is needed. Exclude timestamps and system-generated identifiers if they don't represent meaningful changes. Finally, time a refresh with representative data. A large comparison may belong in a database.
A sensible order to learn the cases
Start with the four order rows. Add a calculated variance to a budget comparison. Try a time-based sales report, then break down a cost. Save the audit version for when the matching logic is familiar enough to attach evidence to each change.
Applying it to your own file
Name the inputs
Create the two Excel tables, give them distinct names and settle on the columns that identify a row in both. Normalize names and types before joining them.
Open the editor
Choose Data → Get Data → From Other Sources → Blank Query, open Advanced Editor and paste the template. Set the two table names and keys to the ones in your workbook.
Check a refresh before relying on it
Choose Close & Load. Verify a known addition, removal, change and unchanged row. Then use a PivotTable to summarize the exceptions.
Every row says Modified. Where do I start?
Look at ChangedCols for one offending row and compare the two recorded values. A number such as 10 and a text value such as "10" look identical on screen. Give both columns the same numeric type. If only repeated order numbers misbehave, look for a sort on one side. For a text-only mismatch, inspect trailing spaces. Microsoft on how Value.Equals compares values
If you know a little SQL
Choosing columns, filtering rows, joining tables and grouping records have familiar counterparts in Power Query. The editor lets me see the result after each step.
| SQL | Power Query | Explanation |
|---|---|---|
| SELECT | Column Selection UI | Only the necessary columns |
| WHERE | Table.SelectRows | Conditional Filtering |
| JOIN | Table.NestedJoin | Merging Tables |
| GROUP BY | Table.Group | Grouping/Aggregation |
| CASE WHEN | if...then...else | Conditional Logic |
| WITH CTE | let...in | Storing Intermediate Results |
I can inspect an intermediate table, revisit an earlier transformation, and load straight back into Excel. That's particularly valuable at month-end when the person checking the answer also understands the spreadsheet.
What I learned about automating an accounting job
Someone still has to know what a row means
A tool can write a join once I specify it. It takes someone who knows the order book to ask whether the second PO-002 line can move and what a missing line means at close. Accounting supplies the question and the acceptance test. Power Query and AI help turn the answer into a repeatable operation.
What changed at my desk
A close that took about three hours with hand-built lookups and visual checks came down to about twenty minutes with refresh and review. I could use the same comparison again next month. The sample reconciled against the expected rows, which gives me something to keep testing as the data changes.
Next month's close
The day after you finish the report, save the two inputs and a few rows whose answers you know. The next month that's more valuable than a beautifully colored spreadsheet. You have a way to tell whether the new result is right.
Filed under accounting, Excel and data analysis.
© 2025 B.J.T. · Boundless Journey of Thought