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 NumberProduct NameQuantityAmount
PO-001Valve A10100,000
PO-002Valve B550,000
PO-002Valve C330,000

The copy returned, P06_Ending

Order NumberProduct NameQuantityAmount
PO-001Valve A15150,000
PO-002Valve B550,000
PO-003Valve D770,000

The four rows the query should return

Order NumberProduct NameChangeTypeQuantity_DiffAmount_Diff
PO-001Valve AModified10 → 15100000 → 150000
PO-002Valve BUnchangednullnull
PO-002Valve CRemovednullnull
PO-003Valve DAddednullnull

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 CodeDepartmentBudget AmountRemarks
SalariesSales50,000,000Monthly
SalariesAdministration30,000,000Monthly
Staff welfareSales5,000,000
Staff welfareAdministration3,000,000
TrainingAdministration2,000,000

Actual spend, Actual_2025

Account CodeDepartmentActual spendRemarks
SalariesSales52,000,000More overtime
SalariesAdministration29,500,000One employee left
Staff welfareSales5,200,000
Staff welfareAdministration2,500,000Event cancelled
Marketing expensesSales10,000,000New 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 CodeDepartmentChangeTypeBudget AmountActual spendBudget_DiffActual_DiffChangedCols
SalariesSalesModified50,000,00052,000,000nullnull["Actual Amount","Remarks"]
SalariesAdministrationModified30,000,00029,500,000nullnull["Actual Amount","Remarks"]
Staff welfareSalesModified5,000,0005,200,000nullnull["Actual Amount"]
Staff welfareAdministrationModified3,000,0002,500,000nullnull["Actual Amount","Remarks"]
TrainingAdministrationRemoved2,000,000nullnullnullnull
Marketing expensesSalesAddednull10,000,000nullnullnull

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 CodeDepartmentChangeTypeBudget AmountActual spendVarianceVariance (%)Review flag
SalariesSalesModified50,000,00052,000,000+2,000,000+4.0null
SalariesAdministrationModified30,000,00029,500,000-500,000-1.7null
Staff welfareSalesModified5,000,0005,200,000+200,000+4.0null
Staff welfareAdministrationModified3,000,0002,500,000-500,000-16.7⚠️ Important
TrainingAdministrationRemoved2,000,000null-2,000,000nullnull
Marketing expensesSalesAddednull10,000,000+10,000,000nullnull

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.

DepartmentTotal BudgetActual spendVarianceBudget utilization (%)
Sales55,000,00067,200,000+12,200,000122.2
Administration35,000,00032,000,000-3,000,00091.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 CodeRegionSales AmountUnits sold
PROD-ASeoul100,000,0001,000
PROD-ABusan50,000,000500
PROD-BSeoul80,000,000800
PROD-BBusan40,000,000400
PROD-CSeoul30,000,000300

October sales, Sales_202410

Product CodeRegionSales AmountUnits sold
PROD-ASeoul120,000,0001,200
PROD-ABusan45,000,000450
PROD-BSeoul85,000,000850
PROD-BBusan42,000,000420
PROD-DSeoul50,000,000500

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 CodeRegionChangeTypeSeptember SalesOctober SalesSales Growth Rate (%)Units sold Growth Rate (%)Trend
PROD-ASeoulModified100,000,000120,000,000+20.0+20.0📈 High growth
PROD-ABusanModified50,000,00045,000,000-10.0-10.0📉 Caution
PROD-BSeoulModified80,000,00085,000,000+6.3+6.3➡️ Stable
PROD-BBusanModified40,000,00042,000,000+5.0+5.0➡️ Stable
PROD-CSeoulRemoved30,000,000nullnullnull❌ Discontinued
PROD-DSeoulAddednull50,000,000nullnull🆕 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 CodeMaterial Cost (Standard)Labor Cost (Standard)Manufacturing Overhead (Standard)Standard QuantityStandard Rate
PROD-0011,0005002001001,700
PROD-0022,000800300503,100
PROD-0031,500600250802,350

What production recorded, ActualCost

Product CodeMaterial Cost (Actual)Labor Cost (Actual)Manufacturing Overhead (Actual)Actual QuantityActual Unit Price
PROD-0011,2004802201101,900
PROD-0021,950820310483,080
PROD-0031,600650270852,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 CodeChangeTypeStandard CostActual CostMaterial Cost_Quantity VarianceMaterial Cost_Price VarianceTotal Cost VarianceVariance Type
PROD-001Modified1,7001,900+170+2,200+200🔴 Unfavorable Variance
PROD-002Modified3,1003,080-310-96-20🟢 Favorable Variance
PROD-003Modified2,3502,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 NumberAsset NameAcquisition CostAccumulated DepreciationBook ValueDepartment
FA-001Server Equipment10,000,0006,000,0004,000,000IT
FA-002Vehicle30,000,00015,000,00015,000,000Sales
FA-003Office Equipment5,000,0003,000,0002,000,000Administration

Closing register, FixedAssets_After

Asset NumberAsset NameAcquisition CostAccumulated DepreciationBook ValueDepartment
FA-001Server Equipment10,000,0006,200,0003,800,000IT
FA-002Vehicle30,000,00015,500,00014,500,000Sales
FA-004Multifunction printer3,000,00003,000,000Administration

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 NumberAsset NameChangeTypeChangedColsImportanceReviewed atReviewer
FA-001Server EquipmentModified["Accumulated Depreciation","Book Value"]📝 Normal Depreciation2025-10-04 15:30bjt
FA-002VehicleModified["Accumulated Depreciation","Book Value"]📝 Normal Depreciation2025-10-04 15:30bjt
FA-003Office EquipmentRemovednull⚠️ Disposal/Sale2025-10-04 15:30bjt
FA-004Multifunction printerAddednull🆕 New Acquisition2025-10-04 15:30bjt

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.

SQLPower QueryExplanation
SELECTColumn Selection UIOnly the necessary columns
WHERETable.SelectRowsConditional Filtering
JOINTable.NestedJoinMerging Tables
GROUP BYTable.GroupGrouping/Aggregation
CASE WHENif...then...elseConditional Logic
WITH CTElet...inStoring 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

Turn the result into a dashboard