Spreadsheets for Business Decisions

IIM Bangalore BBA in Digital Business and Entrepreneurship · Term 3 · 4 modules, 191 topics.

Business Applications

Introduction to Module 4

Why finance now?
Modules 1–3 built operational and marketing intelligence from spreadsheets. Module 4 closes the loop by adding finance — the language of business performance. The capstone task: act as a business analyst asked by the CFO to prepare a profit and loss statement (P&L) for the year and derive a management information system (MIS) report for investors and the CEO.

Recap of Modules 1–3

ModuleFocusKey Tools & Techniques
1Data capture & organisation (sales, purchases, inventory)Basic sheets, ordering decisions
2Sales analyticsPivot tables, dashboards, trend visualisation
3Advanced marketing analytics (invoice line‑level data)Cohort analysis, customer segmentation

Together they turned raw data into actionable intelligence for inventory/operations, sales, and marketing. The missing piece: finance.

What Module 4 Covers

  1. The Trial Balance (TB) – what it is, how to read it, why it matters.
  2. Build a P&L from a Trial Balance – map TB data into a structured statement.
  3. Analyse percentages, margins, and key ratios within the P&L.
  4. Interpret cost breakdowns and income trends to extract insights.
  5. Cross‑compare marketing data (lead dataset) with the P&L to evaluate marketing efficiency and profitability.

End‑of‑module goal: Use Excel to generate business‑critical financial insights — not just know functions, but apply them to real‑world decision‑making.

Learning Outcome

By the end, you will be someone who can transform a trial balance into a P&L, benchmark metrics, and produce an investor‑ready MIS report. This makes you an indispensable asset in any organisation.

Key takeaways

  • Module 4 adds the finance function to the operational and marketing skills from prior modules.
  • Core artefacts: Trial BalanceProfit & Loss StatementMIS Report.
  • Focus on percentages, margins, ratios, and cost breakdowns for financial insight.
  • Cross‑analysis with marketing data reveals the profitability of marketing spend.
  • The ultimate deliverable is a business‑critical financial insight that supports strategic decisions.

Business Context: A Furniture Startup

The company is a city-based furniture startup producing fixed wooden furniture (wardrobes, kitchen cabinets, beds, shelves) and custom wooden work. Customers order via showroom visits; orders are built in a factory, then delivered and installed. The model is semi-custom – fixed units allow mass production while offering customization of material, finish, and colour. Custom work (tailor-made shape/size) is more expensive and complex. Premium add-on services (civil work, electrical, painting) are high-margin and often bundled.

Billing is stage-wise, tied to project milestones: advance → after design → after manufacturing/delivery → after installation. This creates multiple revenue ledgers per order type.

Order TypeScalabilityComplexityMargin
Standard fixed unitsHigh (predictable sizes)LowLower (competitive)
Custom wooden workLow (bespoke)HighHigher
Add-on servicesMedium (bundled)MediumHighest

The Analyst’s Task: Build an MIS Report

You are a business analyst reporting to the CFO. Your job: create a Management Information System (MIS) report for investors – a summary of business performance across functions. This requires breaking down revenue and expenses from raw accounting data.

The Raw Material: The Trial Balance

The finance team provides a trial balance – a spreadsheet listing every ledger (a category where money is tracked, e.g., rent, salaries, revenue) with debit and credit columns. Each row is a ledger; there are ~120 rows for the year 2024–2025.

Key points about trial balances:

  • Revenue ledgers have a credit balance (money earned or borrowed).
  • Expense ledgers have a debit balance (money spent).
  • In practice, trial balances are split by month, city, or location; centralized costs (e.g., CEO salary) are allocated across branches. The given version is a consolidated annual trial balance for learning.

Understanding the Ledgers

Revenue Ledgers (Credit Balances)

Ledger names reveal business operations. Examples from the transcript:

  • Supply of projects – finished modular furniture (~₹6 crores) – fixed furniture (the core product).
  • Supply of projects – custom wooden workcustom furniture.
  • Supply of civil projectsadd-on civil services.

These ledgers show stage-wise revenue collection (see below).

Expense Ledgers (Debit Balances)

  • Direct costs (variable): COGS (cost of goods sold – hardware, laminates, plywood), Painting charges, Site fitting costs, Civil & plumbing costs, Electrical costs.
  • Salaries (semi-fixed): broken by team – Design, Sales, Marketing, Customer, Technology, Finance, R&D.
  • Fixed overheads: Rent (office & showroom), Bank charges, Interest on bank OD (overdraft), Interest on loans (~₹7 lakhs).
  • Variable marketing: Facebook cost, Google cost.

Revenue Recognition: Stage-Wise Billing

The transcript reveals multiple billing patterns inferred from ledger names and percentages:

Product LineStage 1Stage 2Stage 3Stage 4
Fixed wooden furniture5%15%35%45%
Civil add-on (variant 1)5%40%5%50%
Civil add-on (variant 2)10%40%50%

Each stage corresponds to a project milestone (advance, after design, after manufacturing, after delivery/installation). The percentages sum to 100% per order.

Cost Structure Breakdown

Costs can be classified by behaviour:

  • Variable (direct with order volume): COGS, painting, site fitting, marketing (Facebook/Google).
  • Fixed (independent of volume): rent, salaries (most), interest, bank charges.
  • Semi-fixed: salaries (headcount-driven, not directly per order).

The trial balance includes both – a clue that the P&L must separate COGS from operating expenses (SG&A).

flowchart TD
    A[Walk to Finance Team] --> B[Receive Trial Balance]
    B --> C[Classify Ledgers: Debit vs Credit]
    C --> D{Revenue Ledger?}
    D -->|Yes| E[Group by revenue source]
    D -->|No| F[Group by cost type]
    E --> G[Build P&L: Revenue - Expenses]
    F --> G
    G --> H[Deliver MIS Report to CFO/Investors]

Exam tip: In a trial balance, revenue ledgers always have a credit balance; expense ledgers have a debit balance. When building a P&L, you subtract expenses (debits) from revenues (credits). Misclassifying a ledger’s sign will produce a wrong profit figure.

Key Takeaways

  • The P&L for this furniture startup must be assembled from a trial balance of ~120 ledgers.
  • Revenue is recognized in stages (5%, 15%, 35%, 45% for fixed furniture) – each stage is a separate ledger.
  • COGS and direct costs (variable) are separate from fixed overheads (rent, salaries, interest).
  • The trial balance reveals operations: standard vs custom vs add-on revenue, team salaries, and financing costs (overdraft interest).
  • The analyst must classify each ledger correctly and then group into P&L heads (revenue, COGS, operating expenses, finance costs).

What is a PNL?

A Profit & Loss (PNL) statement is a financial report card that shows revenue earned, costs incurred, and the resulting profit or loss. It is built in layers so that the source of profitability (or leakage) can be identified at each stage.

The Layered Structure

Each layer subtracts a specific category of costs, yielding a new margin that reveals how well the business is performing at that step.

1. Revenue

  • The top line: all income from core products or services.
  • Often split into gross revenue and net revenue (after taxes like GST).
  • For a furniture company: project billing, fixed unit billing, custom woodwork, civil projects.

2. Direct Costs (COGS)

  • Costs directly tied to producing and delivering what was sold (materials, labor, transport, inventory used).
  • Also called Cost of Goods Sold (COGS).

3. Gross Margin (also called Contribution Margin 0) Gross Margin=Net RevenueDirect Costs\text{Gross Margin} = \text{Net Revenue} - \text{Direct Costs}

  • First layer of profit; indicates production and delivery efficiency.
  • High gross margin → efficient operations or low raw material costs.

4. Direct Marketing Expenses

  • Spending specifically to acquire customers for recorded sales: Google/Facebook ads, sales team incentives, offline campaigns.

5. Contribution Margin 1 (CM1) CM1=Gross MarginDirect Marketing Expenses\text{CM1} = \text{Gross Margin} - \text{Direct Marketing Expenses}

  • Profit after production and direct sales effort. Reveals marketing efficiency.

6. Indirect Operating Expenses

  • Costs not tied to a single order: project team salaries, design team salaries, sales team salaries.

7. Contribution Margin 2 (CM2) CM2=CM1Indirect Operating Expenses\text{CM2} = \text{CM1} - \text{Indirect Operating Expenses}

  • Profit after removing as many assignable project costs as possible. Shows whether support teams are overstaffed or underutilized.

8. SG&A (Selling, General & Administrative Expenses)

  • Central costs not directly linked to projects: office rent, showroom rent, HR/finance/admin salaries, software subscriptions.

9. EBITDA \text{EBITDA} = \text{CM2} - \text{SG&A}

  • Earnings Before Interest, Taxes, Depreciation, and Amortization.
  • The headline profit number most investors care about; reflects core business health before financial and accounting adjustments.

Flow Diagram

flowchart LR
    A[Net Revenue] --> B[Minus Direct Costs]
    B --> C[Gross Margin]
    C --> D[Minus Direct Marketing]
    D --> E[CM1]
    E --> F[Minus Indirect Operating]
    F --> G[CM2]
    G --> H[Minus SG&A]
    H --> I[EBITDA]

Why Layer? – Diagnostic Power

If this margin is low……the likely problem is
Gross MarginProduction/material costs too high
CM1Marketing inefficient (too much spend for too little revenue)
CM2Support/indirect teams overstaffed or underutilised
EBITDACore business model itself is unhealthy

Industry Variations

IndustryRevenue SourcesDirect CostsMarketing FocusKey Customizations
SaaS (Software)Monthly subscriptions, usage feesCloud servers, hosting, customer supportPaid campaigns, trials, affiliate fees (often large)Gross margin typically very high; CM1 may be skipped. Recurring profit from core tech operations is isolated.
D2C FashionOnline/offline sales, product categories (shirts, shoes, etc.)Manufacturing, warehousing, deliveryFacebook, Instagram, influencers, email targetingCM1 is crucial (marketing game). Profitability is tracked by collection or category.
Furniture & Civil ServicesDesign fees, advances, post-delivery milestonesMaterial, labor, transportGoogle/Face ads, sales incentivesAll CM layers used; granular tracking helps manage mixed standard/custom projects across geographies. Civil projects especially benefit.

Format Customisation

  • No universal PNL format – the CFO defines one tailored to the business model, cost structure, and reporting needs.
  • A simple business may stop at gross margin. Complex delivery models (heavy marketing, multiple project types) require multiple contribution margins.
  • For a startup, the format is built from the trial balance by grouping ledgers operationally.

Exam tip: The multi-layered PNL is a diagnostic tool. Investors look at EBITDA as the headline, but each intermediate margin pinpoints exactly where profitability leaks – production, marketing, operations, or overhead.

Key Takeaways

  • PNL layers: Revenue → Direct Costs → Gross Margin → (Direct Marketing → CM1) → (Indirect Operating → CM2) → SG&A → EBITDA.
  • Gross margin measures production efficiency; CM1 measures marketing ROI; CM2 measures indirect team utilisation; EBITDA measures core business health.
  • Industry customisation is essential – software, D2C, and services each emphasise different layers.
  • The goal of layering is to isolate the source of profit or loss, enabling targeted fixes.
  • For a startup without a predefined format, the PNL is derived directly from the trial balance.

PNL Analysis – Building a P&L from Ledgers

A P&L statement is built from the ground up by mapping raw ledger accounts (from a trial balance) into a structured hierarchy. The goal is to isolate performance at successive layers: Gross Margin, Contribution Margin 1, Contribution Margin 2, and EBITDA. Each layer strips away a specific category of cost, revealing how different parts of the business drive profitability.

The P&L Staircase

flowchart TD
    A[Gross Revenue] --> B[− GST]
    B --> C[Net Revenue]
    C --> D[− Direct Costs]
    D --> E[Gross Margin]
    E --> F[− Direct Marketing Expenses]
    F --> G[Contribution Margin 1]
    G --> H[− Project Costs]
    H --> I[Contribution Margin 2]
    I --> J[− Central Costs]
    J --> K[EBITDA]

Revenue: Net Revenue and Its Components

Net Revenue is the top-line after tax. It is built from credit ledger accounts (e.g., woodwork booking, woodwork revenue, civil booking, civil revenue, other revenue). The lecture maps each ledger to a sub‑head under Net Revenue.

Ledger ExampleMapped To
5% booking amount (woodwork)Woodwork Booking
Later cost, civil bookingCivil Booking
Other revenue (scrap sales)Other Revenue
Finished modular/furnitureFixed Units Revenue

Net values are assumed (GST is 18%). Gross Revenue is derived by reversing GST:

Gross Revenue=Net Revenue×(1+GST rate)\text{Gross Revenue} = \text{Net Revenue} \times (1 + \text{GST rate})

Direct Costs → Gross Margin

Direct costs are those directly attributable to delivering the revenue. They are split by project type (woodwork + fixed, civil) and include material, labour, installation, factory, and logistics.

Cost CategoryLedger Examples
Material – Wood + FixedHardwares, laminates, plywood, outsourced interior work
Direct Costs – CivilFall ceiling, civil electricity, plumbing, painting, final cleaning
Installation & DeliveryCarpenter costs, inward/outward logistics
Factory CostsFactory operators, security, electricity, generator, warehouse
Rework & WastageSeparate head to track month‑on‑month reduction
Other Direct CostsFitting charges, outsourced activity

Gross Margin=Net RevenueTotal Direct Costs\text{Gross Margin} = \text{Net Revenue} - \text{Total Direct Costs}

Direct Marketing Expenses → Contribution Margin 1

Marketing expenses directly tied to generating leads are separated from general branding. They are grouped as Online, Offline, and Referral.

ChannelLedger Examples
OnlineFacebook, Google, Bing ads, website costs, organic channels
OfflineCall centre, lead purchase, agent/influencer commissions, direct events
ReferralClient referral fees (tracked separately from agent referrals)

Contribution Margin 1=Gross MarginDirect Marketing Expenses\text{Contribution Margin 1} = \text{Gross Margin} - \text{Direct Marketing Expenses}

Project Costs → Contribution Margin 2

Project costs are the salaries and incentives of teams directly serving projects: sales, design, project delivery, and customer support. This layer reveals the utilisation of key resources.

  • Sales team salary & incentives
  • Design team salary & incentives
  • Project & delivery team salary & incentives
  • Site visit costs (design team expense)

Contribution Margin 2=Contribution Margin 1Project Costs\text{Contribution Margin 2} = \text{Contribution Margin 1} - \text{Project Costs}

Central Costs → EBITDA

Central costs are not directly traceable to individual projects or centres. They include office/showroom, central team salaries, consultants, technology, branding, and general administration.

Central Cost HeadExamples
Office & ShowroomRent, maintenance, parking, repairs
Central Team SalariesHR, management, admin, technology, support teams
Consultancy & ProfessionalLegal, recruitment, marketing consultants
TechnologySoftware subscriptions, asset/equipment rentals
General AdminStationery, broadband, travel, staff welfare
Central BrandingBillboard with logo only (non‑lead‑generating)

EBITDA=Contribution Margin 2Total Central Costs\text{EBITDA} = \text{Contribution Margin 2} - \text{Total Central Costs}

Exam tip: EBITDA excludes Interest, Tax, Depreciation, and Amortisation by definition. In this construction, interest is intentionally skipped to stay faithful to EBITDA. If a question asks “where would interest appear?”, answer: after EBITDA, before Net Profit.

Key Takeaways

  • The P&L is built by mapping every ledger from the trial balance into predefined heads, ensuring every cost is assigned to the correct layer.
  • Gross Margin = Net Revenue − Direct Costs (material, labour, factory, logistics).
  • Contribution Margin 1 strips out direct marketing (online/offline/referral) to show profitability after lead generation.
  • Contribution Margin 2 further removes project‑related salaries (sales, design, delivery).
  • EBITDA = Contribution Margin 2 − central costs (office, central teams, tech, admin).
  • The structure allows managers to isolate which layer is underperforming – e.g., low Contribution Margin 1 may indicate inefficient marketing spend.
  • Ledger mapping must be consistent; judgment calls (e.g., whether factory electricity is direct or central) need CFO alignment.

PNL Analysis: Building and Interpreting a Profit & Loss Statement

A profit and loss (P&L) statement summarises revenues, costs, and profitability over a period. Building it from raw ledger data forces a deep understanding of the business; interpreting it reveals where money is made or lost and where to intervene.


Building the P&L from Ledgers

Mapping ledgers to heads

  • Each ledger (e.g., “Fixed Unit Revenue”, “Wood Direct Cost”) is mapped to a P&L head (e.g., “Fixed Units”, “Direct Wooden Costs”).
  • This mapping converts a raw trial balance into a structured statement.

Aggregating values

  • Use SUMIF (or equivalent) to sum all credit ledgers mapped to a head (for revenues) or debit ledgers (for costs).
  • Net each head as credit‑minus‑debit (or vice versa) so revenues are positive and costs are negative.

P&L structure (from top to bottom)

HeadDerivationPurpose
Gross Revenue (GMV)Net Revenue + GSTTotal invoice value
GSTTax collected, not company income
Net RevenueSum of all revenue headsTrue top line
Direct CostsSum of direct material, factory, installation, etc.Cost of goods/services sold
Gross MarginNet Revenue – Direct CostsProfit after direct costs
Indirect Costs (direct marketing, branding)Sum of marketing, branding, referralCustomer acquisition & brand
Contribution Margin 1 (CM1)Gross Margin – Indirect CostsProfit after acquisition costs
Project Costs (design, sales, project team)Sum of team costs tied to projectsDelivery‑related overhead
Contribution Margin 2 (CM2)CM1 – Project CostsProfit before central overhead
Central Costs (office, salaries, consulting, tech)Sum of all corporate overheadFixed operational expenses
EBITDACM2 – Central CostsOperating profit before interest, tax, depreciation, amortisation

Exam tip: The P&L hierarchy isolates profitability at each layer. Gross margin shows unit‑level economics; EBITDA shows overall viability. Comparing % to net revenue across layers reveals where value is destroyed.

Benefits of the subtotal formula

  • Using SUBTOTAL(9, range) instead of SUM allows filtering without breaking totals – filtered rows are excluded automatically.
  • Enables cleaner aggregation when building the P&L in a spreadsheet.

Formatting conventions

  • Bold key P&L lines: Gross Revenue, Net Revenue, Direct Costs, Gross Margin, Contribution Margins, EBITDA.
  • Underline or box critical numbers for visual clarity.

Key takeaways – Building a P&L

  • Every P&L must be built from actual ledgers using a mapping step.
  • Structure layers: revenue → direct costs → indirect costs → project costs → central costs → EBITDA.
  • Use SUBTOTAL for filter‑friendly sums.
  • Always verify the meaning of each ledger with finance/ops teams (ledger names vary by company).

Interpreting the Numbers

Analysis converts numbers into business insights. All percentages are computed against Net Revenue (GST excluded) because tax is not controllable.

Revenue composition

  • Fixed units (catalog wooden furniture): 54% – strongest stream, reliable and repeatable.
  • Civil work: 21% – high margin but operationally complex (low standardisation).
  • Woodworking: 18.59% – strong pipeline (bookings 5%).
  • Miscellaneous: 0.16% – negligible (scrap sales, one‑offs).

Interpretation: The business is anchored by manufactured products; civil projects add margin but risk. Booking percentages (civil 1%, wood 5%) indicate future revenue visibility.

Cost analysis (% of Net Revenue)

Cost head%Insight
Direct Wooden Costs29%Largest cost, slightly high – negotiate vendors, standardise
Factory Costs7.5%Operational, room for optimisation
Installation4.6%Reasonable but reducible (fixed installation)
Other Direct (rework/wastage)2.5%Monitor for leakage
Civil Costs5%Very low relative to 21% revenue → high margin
Direct Marketing (total)10.13%Heavy online (7.91%) – dependency on paid ads
Offline Marketing1%Underutilised channel
Call Center2.01%Combined with offline could be boosted

Margin progression

  • Gross Margin: ~50% – healthy for a physical goods business.
  • CM1 (after marketing): ~40% (implied) – reasonable.
  • CM2 (after project costs): ~27‑30% – still healthy.
  • EBITDA: ~4.6‑5% – positive but thin.

Why is EBITDA so thin?

  • Design cost: 6% – surprisingly high given that 54% of revenue is from standardised fixed units. Could be reduced by 3% through efficiency or software.
  • Central team salaries: 11% – high for a fixed‑cost‑heavy business.
  • Office expenses: ~5.5% (combined) – premium location, potentially trim.

Sensitivity to revenue drop

flowchart LR
  A[Revenue drops to 9 Cr] --> B[EBITDA becomes -30% loss]
  A2[Revenue stays 12 Cr] --> B2[EBITDA +4.6%]
  A3[Revenue rises to 15 Cr] --> B3[EBITDA significantly higher]

At 12 Cr net revenue, the business barely breaks even. If revenue falls to 9 Cr, fixed costs cause a 30% loss. The break‑even is around 11‑11.5 Cr. This fragility is the key strategic risk.

Actionable recommendations

  1. Boost demand for high‑margin product lines (fixed units) via festivals, campaigns, bundles – increase bookings (currently 1‑5%).
  2. Reduce material costs – negotiate fixed‑price vendor contracts, standardise SKUs, bulk procure.
  3. Optimise marketing – reduce online dependency, increase offline/referral (low cost), measure CAC by channel.
  4. Improve design efficiency – fewer designers needed for standard products; automate or repurpose.
  5. Cut central overhead – renegotiate office lease, reduce consulting/tech if not essential.

Exam tip: When analysing a P&L, always ask: “What would happen if revenue fell 20%?” The answer reveals the company’s operating leverage – high fixed costs amplify losses. This is the most testable insight from the analysis.

Key takeaways – Interpreting the P&L

  • Revenue mix reveals which product lines are dependable vs. risky.
  • Cost percentages should be benchmarked – a 29% material cost is high; 5% civil cost is excellent.
  • Gross margin ~50% is okay, but EBITDA <5% is fragile.
  • A small revenue decline turns EBITDA negative; the business needs a revenue buffer or cost reduction.
  • Every number tells a story: connect data to strategy to decide where to double down or cut.

MIS: Building a 360-Degree Business Dashboard

A Management Information System (MIS) is a centralized report that gives stakeholders (CFOs, founders, investors, operations heads) a 360° view of the business. A P&L is only one lens. A strong MIS combines multiple functional area metrics so leadership can spot trends, course-correct quickly, and capitalise on opportunities. Each metric tracked — from marketing cost per lead to project timelines to team efficiency — has a ripple effect; together they form a control panel.

Components of a Full MIS

AreaKey metricsData source / who to ask
MarketingLeads by channel (Google, Facebook, referral, offline), conversion per channel, cost per lead, cost per conversion, average order value (AOV), campaign ROASMarketing team; tools like Facebook Ads Manager, Google Ads, HubSpot, Zoho CRM, internal Excel trackers
InventoryRaw material inflow/outflow, stock aging, unsold materials, monthly consumption vs. plan, vendor delivery delaysPurchasing team, factory/warehouse
Project & DeliveryProjects booked vs. delivered, average order-to-completion time, project delays beyond agreed timelines, SLA compliance (civil, fixed, custom furniture)Project management team, site execution head
Customer SuccessNPS scores, cycle time, bottleneck analysisCustomer success team
Conversion FunnelLead count → site visits → designs sent → bookings → handovers, stage-wise drop-offs, conversion time per leadSales team, CRM team, designer heads
Sales ForecastingLead pipeline by city/product/channel, quotation status, probability per deal, month-on‑month forecast vs. actualSales managers, CRM (Zoho, Salesforce etc.)
Cash Flow & Balance SheetCash in hand, vendor payment delays, receivables, asset purchases, loan repaymentsFinance/accounts, CFO
HR & ProductivityDepartment-wise headcount, cost vs. output, attrition rate, absenteeism, per-person ROIHR head, operations coordinator

Exam tip: An MIS is not just a collection of reports — it is an operating system that ties every department’s metrics together. The power comes when you correlate metrics with actual cost data from the P&L.

Lead Analytics: A Worked Example

To make MIS actionable, we must connect metrics to real costs. Below is a step‑by‑step analysis of lead data extracted from a marketing team’s dump.

Raw Data Structure

The marketing team provided a table with fields:

  • Lead ID (unique)
  • Source (Online – Bing, FB, Google; Offline; Referral)
  • Convert (1 = signed up, 0 = not converted)
  • Type (Fixed, Custom, Civil, or combinations)
  • Signup Order Value (₹ at time of booking)

Missing data identified: signup date, conversion date, demographic data (city, age). These would enable deeper analysis (e.g., average time to convert, regional performance, customer segment targeting).

Pivot Analysis – Conversion Rates by Source

Using a pivot table, we compute conversion rate (converted leads / total leads per source) and lead share (percentage of total leads from each source).

SourceTotal Leads% of Total LeadsConversionsConversion Rate% of Total Conversions
Offline~4,800*~21%~4569.5%~4%
Bing~2,000*~9%~40020%~3%
Referral~1,000*~4%~50050%~4%
Google AdWords~5,500*~24%~1,10020%~9%
Facebook~11,700*~51%~8007%~7%
Total23,000100%3,00013%100%

*Values approximated from transcript context. Facebook generates 51% of leads but only 7% convert; Google and Referral have high conversion rates.

Average Order Value (AOV) by Source

Compute AOV as total signup order value ÷ number of conversions.

SourceTotal Signup Value (₹)ConversionsAOV (₹)
Offline(high)~456~60,000
Bing(moderate)~400~30,000
Referral(highest)~500~60,000
Google AdWords(moderate)~1,100~30,000
Facebook(low)~800~30,000

Referral and Offline show high AOV; Facebook/Bing/Google moderate.

Cost Allocation to Marketing Channels

We now pull actual cost data from the P&L and allocate shared conversion costs (e.g., call centre cost ₹10 lakh) proportionally to leads received.

Cost items from P&L:

  • Bing: ₹54,000
  • Facebook: (approx. ₹40–45 lakh, specific value not given)
  • Google AdWords: ₹40–45 lakh
  • Referral: value from P&L (assume given)
  • Offline: sum of branding + direct offline + allocated portion of ₹10 lakh conversion cost

Allocation method:
For each source, total cost = (source direct cost) + (lead share × ₹10 lakh).

Example for Bing:
Lead share = Bing leads / total leads ≈ 9% → allocated conversion cost = 9% × ₹10 lakh = ₹90,000.
Total Bing cost = ₹54,000 + ₹90,000 = ₹144,000.

Repeat for each source.

Metrics Summary

SourceLeadsConversionsConversion RateAOV (₹)Total Cost (₹)Cost per Conversion (₹)
Offline4,8004569.5%60,000(branding + share)high
Bing2,00040020%30,000144,000360
Referral1,00050050%60,000(cost from P&L + share)~200
Google5,5001,10020%30,000(40L + share)~370
Facebook11,7008007%30,000(40L + share)~500

Exact figures for offline, referral, Google, Facebook direct costs are not given in the transcript; the example demonstrates the method. Facebook has the highest cost per conversion and lowest conversion rate.

Key Insights from the Analysis

  • Facebook generates the most leads (51%) but the worst conversion rate (7%) and relatively low AOV. It burns money relative to results.
  • Referral and Offline yield high AOV (₹60,000) but low lead volume.
  • Google AdWords and Bing have moderate performance with decent conversion rates (20%).
  • Cost per conversion is lowest for Referral and highest for Facebook, suggesting reallocation of budget may improve ROI.

Exam tip: Always bring cost data into conversion analysis. A high conversion rate means little if the channel’s cost per conversion is unsustainable. This is the “ripple effect” – marketing metrics meet P&L numbers.

Key Takeaways

  • An MIS extends beyond a P&L to cover marketing, inventory, operations, customer success, sales forecasting, cash flow, and HR.
  • Each department must provide raw data (Excel dumps, CRM exports) for central consolidation.
  • Lead analytics should combine conversion rates, AOV, and cost per conversion (including allocated shared costs like call centres).
  • The example shows that Facebook’s high lead volume masks poor conversion and high cost; data drives budget reallocation decisions.
  • Missing data (dates, demographics) limits analysis – always push teams to track more granular fields.

P&L Analysis for Marketing Channel Performance

A P&L analysis combined with marketing channel data transforms vague spend into sharp decision points. By cross-referencing lead data, conversion metrics, and actual booked P&L costs, managers can identify which channels win, which leak money, and what levers to pull next month.

Key Metrics for Channel Evaluation

Each channel is assessed using the following metrics, derived from total cost, leads, conversions, and average order value (AOV):

  • Cost per lead (CPL) = total channel cost / total leads
  • Cost per conversion (CPC) = total channel cost / number of conversions
  • Conversion rate = conversions / leads × 100%
  • Average order value (AOV) = total revenue from channel / conversions
  • Cost as % of AOV = (CPC / AOV) × 100% — measures profitability of acquisition

Exam tip: Cost as % of AOV is the most telling metric for channel viability. A channel becomes borderline unviable when this percentage exceeds ~10–12%, unless volumes are strategic.


Channel-by-Channel Analysis

The following data comes from a real P&L across digital channels (Google, Facebook, Referral, Offline, Bing). All costs in ₹.

Google Ads

MetricValue
Conversion rate21.55% (highest among digital)
Cost per lead₹857 (highest)
Cost per conversion~₹3,700
AOV~₹31 (lowest)
Cost as % of AOV~12%
Share of total conversions39% (40% of all)

Insights:
Google users are high-intent — they search actively, leading to high conversion rates. Despite high CPL, cost per conversion is lower than Facebook’s. However, AOV is the lowest, possibly because Google leads research aggressively for best price.
Action: Retain Google but optimize for higher AOV (e.g., retargeting, premium keywords).

Facebook Ads

MetricValue
Conversion rate~7% (low)
Cost per leadVery low (high volume: ≈11,000 leads)
Cost per conversionHigher than Google
AOVSlightly higher than Google
Cost as % of AOV>12% (higher than Google)
Share of total conversions32%

Insights:
Facebook users are low-intent — they sign up while scrolling but convert poorly. High lead volume masks high conversion cost. The cost as % of AOV is borderline unviable unless conversion improves.
Action: Double conversion rate by refining targeting (age, region, purchase behavior, lookalikes), changing creatives, and narrowing to high-intent audiences.

Referral

MetricValue
Conversion rate50% (highest of all)
Cost per lead~₹300 (very low)
Cost per conversionLowest (≈1% of AOV)
AOVHighest among all channels
Cost as % of AOV~1%
Share of conversions11% (from only 3% of total leads)

Insights:
Referral leads are gold — word-of-mouth trust drives ultra-high conversion and AOV. Yet only ~300 referrals from 3,000 customers.
Action: Aggressively scale referral schemes: incentives, loyalty programs, ambassador clubs, community building. Doubling referrals could cut total marketing cost by half and boost EBITDA from 4% to 8%.

Offline

MetricValue
Conversion rate~10% (good; better than Facebook but below Google)
Cost per lead~₹300
Cost per conversion~₹3,700 (similar to Google)
AOVHigh (second to referral)
Cost as % of AOVReasonable (due to high AOV)

Insights:
Offline pulls in higher-ticket customers but volume is moderate. Risk of fake leads from third-party sources (e.g., architects giving leads to multiple firms).
Action: Focus on high-value zones/premium segments; test incentive-led purchases (pay only if converted); improve conversion rate to 20% (Google level).

Bing

MetricValue
Conversion rateVery low volume, data noisy
Cost per leadLow (low competition)
Cost per conversionLow
AOVAverage
Share of conversions~1%

Insights:
Bing is an oddity — efficient but cannot scale. Minimal impact on total business.
Action: Explore if targeting can be expanded; if not, deprioritize.


Cross-Channel Decisions

flowchart TD
    A[Analyze channel metrics] --> B{Share of conversions > 20%?}
    B -->|Yes| C{Is cost as % of AOV > 12%?}
    C -->|Yes| D[Fix channel: improve conversion rate or targeting]
    C -->|No| E[Scale channel: increase budget while maintaining efficiency]
    B -->|No| F{Is conversion rate > 15% and AOV high?}
    F -->|Yes| G[Double down: referral-like channels]
    F -->|No| H[Optimize or deprioritize: test before scaling]

Key strategic actions derived from the analysis:

  • Scale referral aggressively — it is the most ROI-positive channel.
  • Retain Google but optimize for higher AOV.
  • Fix Facebook — poor conversion makes it too expensive; improve targeting and creatives.
  • Focus offline on high-ticket segments; improve lead quality.
  • Treat Bing as a low-volume experiment; don't expect significant scale.

Exam tip: The narrative of an MIS is not a data dump — it cross-references data from different sources to tell where the business is winning and where it is leaking money. A P&L with channel-level metrics is the first step toward building a decision-grade MIS.

Key Takeaways

  • Cost per conversion and cost as % of AOV are the most critical profitability metrics for each channel.
  • Referral leads have the highest conversion rate, highest AOV, and lowest acquisition cost — scale them.
  • Google delivers high-intent traffic but low AOV; optimize for value, not just volume.
  • Facebook is expensive due to low conversion; fix targeting before scaling.
  • Offline works for high-ticket customers; verify lead authenticity and improve conversion.
  • Bing is efficient but cannot scale; deprioritize if expansion fails.
  • A well-structured MIS turns raw data into targeted decision levers for the next quarter.

Module 4 Business Applications – Summary Notes

This module builds the analytical backbone of a business: the Profit & Loss (P&L) statement and the Management Information System (MIS). The goal is to transform raw accounting data into actionable intelligence for operations, marketing, finance, and strategy.

1. Building the P&L from a Trial Balance

The process starts with the trial balance from the accounting team — a list of every ledger account with its debit/credit balance. The task is to structure that flat list into a layered P&L that reveals true profitability.

  • Step 1 – Map ledgers line by line to business‑meaningful categories (e.g., revenue, cost of goods sold, operating expenses). Each ledger must be assigned to the correct P&L section.
  • Step 2 – Create layers (gross profit, EBITDA, net profit) by grouping mapped ledgers and inserting intermediate subtotals.
  • Step 3 – Use formulas (e.g., SUMIF, VLOOKUP, or structured references) to automate the aggregation so the P&L updates automatically when the trial balance is refreshed.

Exam tip: The mapping step is the most error‑prone. A single ledger misclassified (e.g., marketing cost under “admin expenses”) distorts gross margin and operating profit. Always cross‑check ledger descriptions with the business context.

2. Analyzing the P&L

Beyond building the P&L, the module teaches how to read it to identify gaps, inefficiencies, and opportunities.

  • Analyze marketing spends – Drill into specific expense lines to see how costs relate to revenue.
  • Cross‑track with MIS – The P&L is one slice; the MIS integrates data from other teams (e.g., sales, customer support) to explain why the numbers move.

3. Marketing Efficiency Metrics (Funnel Metrics)

By pulling data from other teams, you calculate strategic funnel metrics that link spending to outcomes:

MetricFormulaWhat it reveals
Cost per Lead (CPL)Total marketing spendNumber of leads\frac{\text{Total marketing spend}}{\text{Number of leads}}Efficiency of top‑of‑funnel acquisition
Cost per Convert (CPC)Total marketing spendNumber of conversions\frac{\text{Total marketing spend}}{\text{Number of conversions}}Efficiency of converting leads to customers

These numbers feed directly into decisions: where to increase spend, which channels to cut, and how to improve unit economics.

4. Putting It All Together – The MIS

The MIS (Management Information System) is a cross‑functional dashboard that combines the P&L with operational and marketing data. It allows you to:

  • Track business efficiency in real time.
  • Ask the right questions (e.g., “Why did cost per lead rise while conversion rate dropped?”).
  • Uncover hidden gaps between marketing spend and revenue growth.

Unlike a simple Excel sheet, the MIS built in this module is designed to be dynamic, automated (via formulas and possibly App Scripts), and reusable across reporting periods.


Key takeaways

  • Start with the trial balance → map ledgers → layer the P&L → automate with formulas.
  • The true value is in cross‑tracking: P&L + operational data = MIS.
  • CPL and CPC are core funnel metrics computed from marketing spend and conversion data.
  • Analytical thinking means moving from “what is the number?” to “what does the number mean for the business?”

Clustering and Cohort Analysis

Introduction to Module 3

Module 3 shifts from descriptive analytics (pivot tables, dashboards, logical segmentation) to strategic analytics — understanding why something happened, who it happened to, and what is likely to happen next. This is where data meets marketing strategy.

Four core techniques are introduced:

TechniquePurposeKey Question It Answers
Cohort analysisTrack customer retention over timeAre we retaining customers? Where do they drop off?
Customer lifetime value (CLTV)Estimate long-term revenue potential per customerIs it worth spending X to acquire a user?
RFM analysis (Recency, Frequency, Monetary)Classify customers by buying behaviourWho are our loyal customers? Who is at risk?
K-Means clusteringBuild unbiased, behavioural-based customer segmentsWhat groups emerge naturally from similarity patterns?

Module Flow

flowchart LR
    A[Cohort Analysis<br/>Visualise retention & churn] --> B[Customer Lifetime Value<br/>Calculate & interpret CLTV]
    B --> C[RFM Segmentation<br/>Rank customers by rules]
    C --> D[K-Means Clustering<br/>Machine finds groups]
    D --> E[Apply to real customer data]

Each technique builds on the previous: cohort analysis provides retention baselines → CLTV puts a dollar value on that retention → RFM adds a behavioural ranking → K-Means automates segmentation without guesswork.

Exam tip: The progression from rule-based segmentation (RFM) to statistical clustering (K-Means) is a classic conceptual bridge. Understand that RFM requires manual thresholds, while K-Means uses distance metrics to form groups objectively.

Key takeaways

  • Module 3 moves from what happened to why, who, and what next.
  • Four techniques: cohort analysis, CLTV, RFM, K-Means clustering.
  • Cohort analysis tracks retention over time; CLTV values a customer lifetime.
  • RFM ranks by recency, frequency, monetary value; K-Means finds groups mathematically.
  • All methods are applied to real customer data — theory is immediately operational.

What is Cohort Analysis?

A cohort is a group of users who share a common characteristic, most often the month they signed up or made their first purchase. Cohort analysis tracks how each cohort behaves over time, answering questions like:

  • How many users remain after their first month?
  • Are customers from January more loyal than those from March?
  • Is retention improving over time?

It is widely used in:

DomainApplication
E-commerceMeasuring repeat purchases
SaaSTracking subscriber retention
Mobile appsAnalyzing user drop-off
EdTechMonitoring batch engagement

The core idea: for each cohort, count how many users return in each subsequent period and build a table showing retention across time.


The Data: Understanding the Invoice Dataset

A real transactional dataset (≈400,000 rows) with columns:

ColumnDescription
InvoiceTransaction/order number
StockCodeProduct code
DescriptionItem description
QuantityUnits purchased
PricePrice per unit
Customer IDUnique customer
CountryCustomer’s country
InvoiceDateDate of transaction

Important structure: An invoice can contain multiple line items (same Invoice number, same Customer ID, multiple rows). Raw data is at the invoice line-item level, not summarized per order.

Data cleaning essentials (always verify):

  • ✅ All quantities are positive – delete rows with negative quantity (returns/cancellations).
  • ✅ All prices are positive – remove zero or negative rows.
  • ✅ Remove test product codes or customer IDs (e.g., "test").
  • ✅ Ensure InvoiceDate is in correct date format (Excel may auto-group).

Exam tip: In any real dataset, cleaning is non-negotiable. Cohort results are only as reliable as the underlying data.


Building the Base Table: From Line Items to Customer Orders

Step 1 – Aggregating Line Items into Invoices

Create a pivot table from the clean data:

  • Rows: Customer ID, then Invoice (and optionally InvoiceDate, Country)
  • Values: Sum of Price (or Count of line items to get order size)

This collapses multiple line items into one row per invoice, giving a customer-level purchase history.

Step 2 – Extracting Signup Date (First Transaction per Customer)

Sort the pivot table by Customer ID and then InvoiceDate (oldest first). The first row for each customer is their signup date (cohort anchor). Use VLOOKUP (exact match) to copy this date into a new column for every row of that customer. Because we sorted ascending, VLOOKUP returns the first – i.e., earliest – date.

Step 3 – Encoding Month Numbers

Since the data spans two years (Jan 2009 – Dec 2010), create a continuous month number for each date:

\text{MONTH(date)} & \text{if YEAR(date) = 2009} \\ \text{MONTH(date)} + 12 & \text{if YEAR(date) = 2010} \end{cases} $$ Apply this to: - **Signup month** → becomes the **cohort number** (e.g., Jan 2009 = 1, Dec 2009 = 12, Jan 2010 = 13). - **Invoice month** → becomes **order month**. Each customer is permanently assigned to one cohort based on their signup month. #### Step 4 – Calculating Retention Period For each transaction, compute: $$ \text{RetentionPeriod} = \text{OrderMonth} - \text{CohortNumber} $$ - **0** = the same month as signup (zeroth month) - **1** = one month after signup - **6** = six months after signup, etc. This number tells us *when* a customer made a purchase relative to their own joining month – the key metric for retention tracking. #### Worked Example Consider a customer with: - Signup date: 14 Dec 2009 → CohortNumber = 12 - Another transaction on 18 June 2010 → OrderMonth = 6 (June) + 12 = 18 $$ \text{RetentionPeriod} = 18 - 12 = 6 $$ This customer made a purchase in the 6th month after signing up. One row in the final dataset will have `CohortNumber = 12` and `RetentionPeriod = 6`. --- ### Data Preparation Workflow ```mermaid flowchart TD A[Raw line-item data] --> B[Clean data: remove negatives, test codes, fix dates] B --> C[Create pivot table: Customer ID + Invoice + InvoiceDate] C --> D[Copy pivot as values → base customer-order table] D --> E[Sort by Customer ID, then InvoiceDate ascending] E --> F[VLOOKUP first InvoiceDate → SignupDate per customer] F --> G[Compute CohortNumber from SignupDate] G --> H[Compute OrderMonth from InvoiceDate] H --> I[RetentionPeriod = OrderMonth - CohortNumber] I --> J[Final table ready for pivot analysis] ``` --- > **Exam tip:** The retention period is *not* the number of consecutive months a customer was active – it only marks the months in which a transaction occurred. A customer may have gaps; each gap period simply lacks a row. The final cohort table (pivot) counts unique customers active in each period, not cumulative. **Key takeaways** - **Cohort = group sharing a common event** (here, first purchase month). - **Retention = activity in a specific month after signup**, measured as order month minus cohort month. - Data must be at invoice level (not line-item) before extracting signup dates. - VLOOKUP with sorted data correctly fetches the earliest transaction date. - Month numbering across years uses an IF-based offset (year → month + 12). - The prepared dataset contains for each row: Customer ID, CohortNumber, RetentionPeriod – ready for a pivot table that counts customers per cohort per period. ### Cohort Analysis: Building and Interpreting Retention Tables A **cohort retention table** tracks what fraction of customers from a given signup period (cohort) remain active in each subsequent period. The goal: see where customers drop off and compare retention across cohorts. ### Building the Retention Cohort Table 1. **Raw pivot** – Place: - **Rows** = `SignupCohortNumber` (the month they first ordered) - **Columns** = `OrderMonth` - **Values** = Distinct count of Customer ID The raw result shows, for each cohort, how many distinct customers placed an order *in each calendar month*. This is *not* retention — it mixes months before and after signup and doesn’t align the time axis. 2. **The retention fix** – Replace `OrderMonth` with **RetentionMonth** = month offset from the cohort’s start. *Example*: if a customer signed up in January (cohort 1) and placed an order in March, retention month = 2. This is typically computed by subtracting the cohort’s start month from the order month. 3. **Result** – Columns become `0, 1, 2, …` months after signup. - Column 0 = month of signup (all customers who ever ordered are counted). - Column 1 = customers who placed at least one order in the next month, etc. | Cohort | Month 0 | Month 1 | Month 2 | … | |--------|---------|---------|---------|---| | 1 | 95 | 53 | 44 | … | | 2 | 88 | 50 | 38 | … | > **Important**: Use **distinct count of customers**, not order count. A customer who orders multiple times in the same month still counts as one retained. ### Interpreting the Raw Table The raw numbers are absolute counts — a cohort with more signups naturally has larger absolute retention. To compare cohorts directly, standardize: - Percentage of the original cohort that returned in each subsequent month. $$ \text{Retention rate}_{c,m} = \frac{\text{# distinct customers in cohort } c \text{ in month } m}{\text{# distinct customers in cohort } c \text{ in month } 0} \times 100\% $$ - Apply **conditional formatting** (e.g., red–white–green heat map) to quickly spot patterns. #### Example (Cohort 1, from transcript) - Month 0: 95 (100%) - Month 1: 53 → 55.8% - Month 2: 44 → 46.3% - Month 3: 52 → 54.7% (possible variation) After 12 months, sharp drop-off. ### Analyzing the Cohort Table Analysis works along three axes: ``` Horizontal → For one cohort: how retention evolves over time Vertical → For one month offset: how retention changes across cohorts Diagonal → For equal customer age: compare cohorts at same distance from signup ``` #### Horizontal (within a cohort) - Look at a single row from left to right. - **What it reveals**: The natural decay of customer activity. A steep drop suggests a specific churn trigger. - *Transcript example*: Every cohort shows a severe drop after month 11 or 12 → likely a 12‑month subscription ending. #### Vertical (across cohorts, same offset) - Compare retention rates for the same month offset across different cohorts. - **What it reveals**: Whether later cohorts are “stickier” or less engaged from the start. - *Transcript example*: Recent cohorts have lower month‑1 retention than older cohorts → the company’s initial engagement activities may have degraded (fewer calls, worse onboarding). #### Diagonal (equal customer age) - Follow cells where cohort + offset = constant (e.g., all customers exactly 12 months old). - **What it reveals**: External events affecting all cohorts equally (e.g., a platform change, marketing shift). - *Transcript comment*: After the 12th month, diagonals turn red → something systemic happened (new software, changed marketing manager). ### Business Insights and Next Steps - **12‑month churn** → Investigate: Are retention emails not going out? Does the subscription auto‑expire? - **Declining early retention** → Review onboarding, first‑month engagement, or product changes. - **Systemic drop** → Cross‑check with company events (software update, leadership change). The same cohort framework can be reused for: - **Average order value** per cohort per month. - **Geographic cohorts** (e.g., by region). - **Acquisition channel** cohorts. This feeds directly into **customer lifetime value (LTV)** calculation in the next step. > **Exam tip**: The most common mistake is using raw order counts instead of distinct customers. Also, never compare absolute numbers across cohorts – always use percentages. **Key takeaways** - A retention cohort table rows = signup cohorts, columns = months since signup. - Use **distinct count of customers** and **offset months**. - Standardize to percentage for cross‑cohort comparability. - Analyze **horizontally** (cohort decay), **vertically** (cohort quality trend), and **diagonally** (external shocks). - Drops after a fixed month (e.g., 12) suggest a systemic cause; declining early retention points to weakening initial engagement. ### Customer Lifetime Value (LTV) Calculations **Customer Lifetime Value (LTV)** predicts the total **revenue** or **profit** a business expects from a single customer over the entire relationship. Intuitively: if you acquire a customer today, how much money will they bring before they stop buying? LTV is the bridge between user behavior and business value. ### Why LTV Matters - **Marketing** – determines how much to spend to acquire a customer (compare with **Customer Acquisition Cost (CAC)**). - **Product** – identifies high-value users to design better experiences. - **Finance** – estimates long-term revenue potential. > **Fundamental rule:** If $LTV > CAC$, the business model works; otherwise, you lose money on every customer. ### LTV Formulas Two common versions: | LTV Type | Formula | Meaning | |----------|---------|---------| | Revenue‑based | $ \text{LTV} = \text{AOV} \times \text{Frequency} \times \text{Lifespan} $ | Total revenue per customer | | Profit‑based | $ \text{LTV} = \text{AOV} \times \text{Frequency} \times \text{Lifespan} \times \text{Gross Margin} $ | Total profit per customer (after direct costs) | Where: - **AOV** = Average Order Value (e.g., ₹100) - **Frequency** = average purchases per time period (e.g., 2 per month) - **Lifespan** = average duration a customer remains active (e.g., 5 months) - **Gross Margin** = profit percentage on each order (e.g., 30%) #### Worked Example (from transcript) > A customer has: lifespan = 5 months, frequency = 2 orders/month, AOV = ₹100, gross margin = 30%. **Revenue LTV**: $$ \text{LTV}_{\text{rev}} = 100 \times 2 \times 5 = ₹1000 $$ **Profit LTV**: $$ \text{LTV}_{\text{profit}} = 1000 \times 0.30 = ₹300 $$ If CAC is ₹150, the business retains ₹150 per customer to cover overheads. ### Estimating Lifespan from Retention / Churn Often companies provide a **retention rate** (e.g., monthly 80%). The **churn rate** is the complement: $\text{Churn} = 1 - \text{Retention}$. For constant churn, average lifespan is: $$ \text{Average Lifespan} = \frac{1}{\text{Churn Rate}} $$ **Example**: 80% monthly retention → 20% churn → average lifespan = $1/0.20 = 5$ months. | Retention Rate (monthly) | Churn Rate | Average Lifespan | |--------------------------|------------|------------------| | 90% | 10% | 10 months | | 80% | 20% | 5 months | | 70% | 30% | 3.33 months | | 50% | 50% | 2 months | > **Exam tip:** The $1/\text{churn}$ formula assumes constant churn over time. For more accuracy—especially when retention changes across cohorts—use a weighted average from cohort data. ### Cohort‑Based LTV Calculation Building LTV per cohort from retention data gives more granular insight. Three components must be derived from the pivot tables: 1. **Average Order Value (AOV)** – average of invoice values per cohort. 2. **Purchase Frequency** – average number of orders per month per customer. 3. **Lifespan** – weighted average of how many months customers remain active. #### Step‑by‑Step (using Excel/Pivot Tables) **Step 1: AOV per cohort** Create a pivot with `Cohort Number` on rows and `Average of Price` (invoice value) as values. This gives the mean order value for each cohort. **Step 2: Frequency per cohort** - Create a pivot with `Cohort Number` on rows, `Order Month` on columns. - Add `Distinct Count of Invoice` (number of orders) and `Distinct Count of Customer ID` (active customers per month). - For each month, compute: $$ \text{Frequency}_{\text{cohort, month}} = \frac{\text{Orders}}{\text{Customers}} $$ - Then average those monthly frequencies across all available months to get a single average frequency for the cohort. **Step 3: Lifespan per cohort** - Create a pivot of `Distinct Count of Customer ID` per cohort per month (like a retention table). - Compute **weighted average lifespan** using the surviving customer counts: $$ \text{Lifespan}_{\text{cohort}} = 1 + \frac{\sum_{t=0}^{T} (\text{Customers at month } t) \times t}{\sum_{t=0}^{T} \text{Customers at month } t} $$ (Add 1 because month 0 represents the first month of activity.) **Example**: If 12 customers total: 6 survive to month 0, 4 survive to month 1, 2 survive to month 2: $$ \text{Lifespan} = 1 + \frac{(6 \times 0) + (4 \times 1) + (2 \times 2)}{6+4+2} = 1 + \frac{0+4+4}{12} = 1 + 0.667 = 1.667 \text{ months} $$ **Step 4: Calculate LTV** For each cohort: $$ \text{LTV}_{\text{cohort}} = \text{AOV}_{\text{cohort}} \times \text{Frequency}_{\text{cohort}} \times \text{Lifespan}_{\text{cohort}} $$ Multiply by gross margin for profit‑based LTV. #### Example of Cohort LTV (from transcript data) | Cohort | AOV (₹) | Frequency (orders/month) | Lifespan (months) | Revenue LTV (₹) | |--------|---------|--------------------------|-------------------|-----------------| | 1 | 74 | 1.3 | 7.1 | 74 × 1.3 × 7.1 ≈ 683 | | 2 | ... | 1.5 | 6.0 | ... | As lifespan and frequency decline across cohorts, LTV shrinks—highlighting the need to analyze which cohorts are truly valuable. ### Insights from Cohort LTV Analysis - A high initial order volume does not guarantee retention; frequency can drop sharply (e.g., post‑month 12). - Comparing LTV vs. CAC per cohort shows whether marketing spend is justified. - Tracking LTV trends over cohorts reveals whether customer quality is improving or degrading. **Key takeaways** - **LTV** = AOV × Frequency × Lifespan (revenue) or × Gross Margin (profit). - **Lifespan** can be estimated as $1/\text{churn rate}$ (constant churn) or via weighted average from cohort retention data. - Cohort‑based LTV uses AOV, frequency, and lifespan calculated from pivot tables on transactional data. - LTV > CAC is the fundamental viability condition. - Cohort LTV analysis reveals differences in customer value over time and across acquisition periods. ### RFM Segmentation **RFM** (Recency, Frequency, Monetary) is a data-driven method to segment customers based on three behavioral indicators. Intuitively: a customer who bought yesterday, buys often, and spends a lot is highly valuable; one who hasn't bought in months needs re-engagement. RFM quantifies these dimensions and assigns each customer a score or category. ### What Each Dimension Captures | Dimension | Definition | Interpretation | |---|---|---| | **Recency** | How recently a customer last made a purchase (e.g., days since last order) | High recency → recently active → more likely to return | | **Frequency** | How often a customer purchases (e.g., orders per month or year) | High frequency → regular/loyal customer | | **Monetary** | How much money a customer has spent in total | High monetary → big spender, worth retaining at any cost | ### Why RFM Matters RFM enables targeted marketing by matching the message to customer behaviour: - **High recency + high frequency + high monetary** → VIP treatment. - **High frequency but low monetary** → potential for upselling. - **Low recency** → re-engagement campaign needed. Unlike arbitrary business‑intuition buckets (e.g., “over ₹1,00,000 is good”), RFM uses **data‑driven quartiles or percentiles**, making segmentation objective and repeatable. ### Computing RFM in Excel (Practical Walkthrough) The process starts with transaction-level data: each row contains a customer ID, invoice date, quantity, and price. The key data preparation step is computing **invoice value** = `Quantity × Price` (not price alone). 1. **Monetary** - From a pivot table with `Customer ID` as rows, add `Sum of Invoice Value` to values. This gives total spend per customer. - Optionally add `Average of Invoice Value` for average order value. 2. **Recency** - Add `Invoice Date` to values and set its aggregation to **Max** (gives the most recent purchase date). Format as short date. 3. **Frequency** - Frequency = number of orders per time unit (e.g., orders per month). - To compute: count the number of invoices per customer (using `Count of Invoice Date`) and divide by the number of months in the dataset. - *Alternative:* create a numeric month index (e.g., month 1 for Jan 2009, month 13 for Jan 2010) and use it to compute orders per month directly. > **Exam tip:** Always use `Quantity × Price` for monetary value, not price alone. A single item price does not reflect total spend; the product gives the true value of an invoice. ### Data‑Driven Segmentation vs. Arbitrary Buckets The previous module used manual revenue brackets (e.g., > ₹1,00,000 = “very good”). These were **business intuition‑based buckets** — subjective and not replicable. RFM replaces them with **quartile or percentile thresholds** that are statistically derived, making segmentation consistent and comparable. ### Key Takeaways - RFM stands for Recency, Frequency, Monetary — three behavioural dimensions of customer value. - High recency → active; high frequency → loyal; high monetary → high spender. - RFM enables targeted messaging: VIP, upsell, re-engage. - Computation: Sum of Value (Monetary), Max Date (Recency), Count of Invoices ÷ Periods (Frequency). - Always compute invoice value as quantity × price. - RFM segmentation is data‑driven (quartiles) and superior to arbitrary revenue brackets. ### RFM Segmentation-II RFM (Recency, Frequency, Monetary) segments customers based on how recently they purchased, how often they buy, and how much they spend. The goal: turn raw transaction data into integer buckets (e.g., 1–4) so that **higher is better** for all three dimensions, then combine them into interpretable customer groups. ### Step 1: Compute raw R, F, M metrics | Metric | Definition | Formula (per customer) | |---|---|---| | **Recency** | Months since last order | $\text{DATEDIFF}(\text{last\_invoice\_date}, \text{analysis\_date}, \text{"M"})$<br>Analysis date = 2011-01-01 | | **Frequency** | Yearly order count | $\frac{\text{count of invoices}}{2}$ (data spans 2 years) | | **Monetary (Total)** | Sum of all order values | `SUM(amount)` per customer | | **Monetary (Average)** | Average order value | $\frac{\text{total value}}{\text{count of invoices}}$ | > **Exam tip:** Recency uses *months since last order* – lower is better. Frequency and monetary: higher is better. To keep a consistent “higher is better” scale, you must **invert recency** before bucketing. --- ### Step 2: Normalize to percentile buckets Manual thresholds (e.g., “orders > ₹1,00,000”) break when data shifts month to month. Instead, use **percentile rank** to create stable, data-driven buckets. 1. **Compute percentile** for each raw metric using `PERCENTRANK.EXC(array, value, significance)`. – Returns a number between 0 and 1 representing where the value lies in the distribution. 2. **Convert to bucket** (e.g., 4 quartiles): $$ \text{bucket} = \text{CEILING}(\text{percentile} \times \text{num\_buckets}, 1) $$ - Multiply by 4 for quartiles, by 10 for deciles, etc. - `CEILING` rounds up to the nearest integer → ensures every value gets a bucket from 1 to `num_buckets`. | Percentile range | ×4 | Ceiling | Bucket | |---|---|---|---| | 0.10 | 0.40 | 1 | 1 (lowest quartile) | | 0.31 | 1.24 | 2 | 2 | | 0.65 | 2.60 | 3 | 3 | | 0.98 | 3.92 | 4 | 4 (top quartile) | **Applying to each RFM dimension:** - **Monetary (Total & Average):** higher percentile → higher bucket → better. - **Frequency:** higher yearly frequency → higher bucket → better. - **Recency:** because raw months-since-last-order is *lower* when better, invert the measure **before** the percentile step: $$ \text{inverted\_recency} = \text{max\_months} - \text{months\_since\_last\_order} $$ where `max_months` = 24 (the full time span of the data). Then compute percentiles and buckets on `inverted_recency`. Now a bucket of 4 means the customer ordered recently. --- ### Step 3: Combine buckets into segments With each customer having three bucket values (R_bucket, F_bucket, M_bucket), you can define interpretable segments: | Segment | R bucket | F bucket | M bucket | Interpretation | |---|---|---|---|---| | Super Loyal High Value | 4 | 4 | 4 | Buys often, spends a lot, just purchased | | At Risk VIP | 1 | 4 | 4 | Used to spend and buy frequently, but hasn’t returned | | New High Spender | 4 | 1 | 4 | Recently made a large purchase, but low frequency | | Lost Low Value | 1 | 1 | 1 | Not recent, rarely buys, low spend | You can create custom logic (e.g., “if all four are 4 → Champions”, “if R≥3, F≥3, M≥3 → Loyal”) depending on business goals. --- ### Why percentile-based bucketing matters - **No manual thresholds** – adapts automatically to changes in purchasing patterns. - **Stable across time** – top 10% this month remains top 10% next month, even if absolute values drop. - **Interpretable** – quartiles (1–4) are easy to explain and combine. --- ```mermaid flowchart TD A[Raw transaction data] --> B[Group by customer] B --> C[Compute Recency, Frequency, Monetary] C --> D[Invert Recency: max_months - months_since_last] D --> E[Compute PERCENTRANK.EXC for each metric] E --> F[Multiply by 4, apply CEILING to get 1–4 buckets] F --> G[Combine R, F, M buckets into segments] G --> H[Target campaigns, loyalty, churn prediction] ``` **Key takeaways** - **RFM** = Recency (months since last order), Frequency (yearly count), Monetary (total & average order value). - Convert raw metrics to percentile buckets (e.g., 4 quartiles) to remove manual bias and ensure stability. - **Invert recency** before bucketing so that higher buckets always mean better behaviour. - Use `PERCENTRANK.EXC` + `CEILING` to get integer buckets. - Combine buckets into segments (e.g., “Super Loyal”, “At Risk”) for targeted marketing and churn analysis. - Percentile-based bucketing works even when absolute values vary month to month – the top 10% stay the top 10%. ### Summary of Module 3 This module delivers four interlocking tools to understand customer behavior and drive retention. Together they form an analytics toolkit for smarter marketing and product decisions. ### 1. Cohort Analysis **Cohort analysis** tracks groups of customers who share a common first-action date (e.g., first purchase) and measures their retention over time. It reveals how user engagement decays after the initial experience, and which cohorts behave differently. ### 2. Customer Lifetime Value (CLV) **Customer lifetime value (CLV)** quantifies the total revenue (or profit) a customer is expected to generate over their entire relationship with the business. It turns retention data into a financial metric, enabling investment decisions about acquisition and retention spend. ### 3. RFM Segmentation **RFM segmentation** classifies customers using three behavioural dimensions: - **Recency** – time since last purchase - **Frequency** – number of purchases - **Monetary value** – total spend These dimensions create clear, human‑interpretable segments (e.g., “best customers”, “at‑risk”); each segment can be targeted with tailored campaigns and engagement strategies. ### 4. Clustering **Clustering** applies statistical algorithms (e.g., k‑means) to let the data form its own natural groupings. Unlike RFM (where rules are defined manually), clustering is machine‑driven and can uncover unexpected patterns that complement human‑designed segments. #### RFM vs. Clustering | Feature | RFM Segmentation | Clustering | |---|---|---| | Basis | Pre‑defined rules (Recency, Frequency, Monetary) | Data‑driven statistical grouping | | Interpretability | High – each segment has clear meaning | Moderate – may require post‑hoc interpretation | | Flexibility | Fixed dimensions | Can incorporate many variables | | Best use | Quick, actionable customer tiers | Deeper discovery of hidden segments | > **Exam tip:** The core distinction is **human‑defined rules** (RFM) vs. **machine‑driven discovery** (clustering). Know that they are complementary, not competing – clustering can reveal segments RFM would miss, and RFM segments are easier to act on directly. **Key takeaways** - Cohort analysis, CLV, RFM, and clustering together answer: *Who are our customers, how much are they worth, and how do they change over time?* - **Cohort analysis** tracks retention of groups over time; **CLV** gives a dollar value per customer. - **RFM** is rule‑based and intuitive; **clustering** is algorithmic and exploratory. - Use both RFM and clustering to combine actionability with discovery.

Data Insights and Dashboard Creation

Introduction to Module 2

This module transitions from storing and structuring data (Module 1) to understanding, visualizing, and telling a story with data. The goal: turn raw data into business insights through interactive dashboards.

What you will learn

TopicPurpose
Pivot tables & pivot chartsFoundational building blocks for interactive dashboards
Sales dashboardBuilt using real data from a vegetable delivery app
Cluster‑wise sales analysisIdentify top‑performing regions
Customer behavior & demand patternsUnderstand what drives purchases
Return volumesSpot products with high return rates
Interactive filters & slicersLet managers drill down dynamically
Professional dashboardPresent clearly to management or clients

The core philosophy: Dashboards for decisions

A dashboard is not a collection of charts — it is a tool that helps a manager answer specific business questions. Every element on the dashboard should serve a decision.

Dashboards are not about creating charts. They're about decisions.

Decision questions a good dashboard answers

A well‑designed dashboard enables quick answers to questions like:

Business questionDashboard insight it surfaces
Is sales going up?Sales trend over time
Which region is underperforming?Cluster‑wise sales comparison
Which product has the highest returns?Return volume by product
Which customer should we focus on?Customer behavior / demand patterns

How the module unfolds

  1. Pivot tables & pivot charts – understand the mechanics.
  2. Build a sales dashboard using a vegetable‑delivery app dataset.
  3. Analyze cluster‑wise sales – uncover top and weak regions.
  4. Examine customer behavior – demand patterns and return volumes.
  5. Compile everything into a clean, professional dashboard.

Exam tip: Memorise the four sample business questions above — they are typical of what a dashboard should answer. Expect a question that asks you to match a dashboard element to a decision.

Key takeaways

  • This module moves from data storage (Module 1) to data insight via visualisation.
  • Pivot tables and pivot charts are the core tools for interactive dashboards.
  • Dashboards are decision‑centric, not chart‑centric.
  • Real example used: a vegetable delivery app (sales, cluster, returns, customer behaviour).
  • By the end, you can build a professional dashboard in Excel or Google Sheets with filters and slicers.

Pivot Tables - I

A pivot table is a spreadsheet feature that automatically reorganises and summarises selected columns and rows from a raw data table into a compact, flexible report. It does not change the original data — it creates a new summary view. Technically, a pivot table is a form of cross tabulation; it gets its name because you can pivot (rotate) the summary around different variables. With drag-and-drop fields, you can instantly group thousands of rows by product, city, date, customer, etc., and switch between monthly totals, category breakdowns, or top-selling SKUs.

Main Components

A pivot table is built from four core areas:

ComponentFunctionExample from transcript
RowsVariables placed here become row labels (one row per unique value)Product (Potato, Tomato)
ColumnsVariables placed here become column headers (one column per unique value)City (Bangalore, Chennai, Mumbai)
ValuesThe numeric field(s) to be aggregated (sum, count, average, max, etc.)Quantity – summed by default
FiltersRestrict the entire pivot table to a subset of data (e.g., date range, city)Optional – not used in the example

Definition (from Wiki): “A pivot table is a table of values which are aggregations of groups of individual values from a more extensible table.” — it takes one detailed table and produces a summary view.

Pivot Charts

Once a pivot table is ready, you can build a chart on that pivot data – a pivot chart. This is a dynamic visual representation of the pivot table. In short: pivot tables summarise; pivot charts visualise.

Worked Example: Vegetable Sales Data

A small dataset of vegetable sales across three cities contains: Date, City, Product (Potato/Tomato), Quantity, Sale Price, and Total Value.

Steps to create a pivot table (Excel):

  1. Select the dataset → Insert → Pivot Table.
  2. Choose location (existing sheet or new worksheet).
  3. The PivotTable Fields pane appears with all column headers.
  4. Drag Product into Rows, City into Columns, and Quantity into Values.

Result (first orientation – product rows, city columns):

ProductBangaloreChennaiMumbaiGrand Total
Potato253550100
Tomato(implicit, not shown)

By swapping rows and columns (or adding filters), you can instantly re-orient the summary — e.g., city as rows, product as columns — to view total sales per city.

Modifying calculations: By default, pivot tables sum numeric values. You can change the aggregation by opening Value Field Settings and choosing Count, Average, Max, Min, etc.

Exam tip: The Value Field Settings menu is where you switch between aggregation functions (Sum, Average, Count, Max, Min). Forgetting this is the most common reason a pivot table gives unexpected numbers.

Key Takeaways

  • A pivot table summarises large datasets without altering the raw data — it creates a new aggregated view.
  • The four main components: Rows, Columns, Values, Filters.
  • Drag fields into these areas to instantly group and summarise.
  • Default aggregation for numeric fields is Sum; use Value Field Settings to change it.
  • A pivot chart is a dynamic chart linked to a pivot table – summary + visualisation.
  • Pivoting (swapping rows and columns) lets you quickly explore different perspectives of the same data.

Understanding the Data Before Pivoting

Real analysis starts with understanding what the data represents, its granularity, and how sheets relate.

Two sheets in the workbook:

  1. SKU Sales Trends – daily SKU-level summary data (dates Jan–Mar 2018, ~700 rows). Columns: Date, SKU Name, SKU Total Orders, Vegetable Orders, Fruit Orders, Sale Price, Billed Tonnage, Return Tonnage.
  2. Customer Level SKU – transaction-level data (Feb only, different SKUs, includes Customer ID, Locality, Quantity, etc.). Not directly related to the first sheet.

SKU = Stock Keeping Unit – the smallest inventory unit (e.g., tomatoes: Standard vs. Hybrid are two SKUs).

Key observation: The SKU Sales Trends table is already aggregated at a daily level. Values like “Total Orders” are attributes of the date, not the SKU. These values repeat across all SKUs for the same date. Therefore, when building a pivot, Sum would double-count – use Max, Min, or Average instead.

Decomposing Order Types Using Set Theory

From the daily summary:

  • U=Total Orders|U| = \text{Total Orders} (all orders)
  • V=Vegetable Orders|V| = \text{Vegetable Orders} (orders with ≥1 vegetable)
  • F=Fruit Orders|F| = \text{Fruit Orders} (orders with ≥1 fruit)

These sets overlap (an order can contain both). To find exclusive categories:

VF=V+FUOnly Veg=VVFOnly Fruit=FVF\begin{aligned} |V \cap F| &= |V| + |F| - |U| \\ \text{Only Veg} &= |V| - |V \cap F| \\ \text{Only Fruit} &= |F| - |V \cap F| \end{aligned}

Example (one day): Total = 1324, Veg = 1289, Fruit = 702
VF=1289+7021324=667|V \cap F| = 1289 + 702 - 1324 = 667
Only Veg = 1289667=6221289 - 667 = 622
Only Fruit = 702667=35702 - 667 = 35

These derived columns are computed directly in Excel (or any analysis tool) and added to the source table.

Building the Pivot Table & Chart

Steps:

  1. Select the data table (including new columns).
  2. Insert Pivot Table, choose new worksheet, optionally check “Add this data to Data Model”.
  3. Set Rows = Date (un-group from months to show days).
  4. Add Values for: Total Orders, Only Veg, Only Fruit, Both. Change each to Max (or Min – identical per date).
  5. Insert Pivot Chart (Line chart) from the pivot.
  6. Add trend lines (linear) to key series.

Insight from the chart:

  • All categories grow over time.
  • The “Both Veg & Fruit” order count has a steeper slope than “Only Veg” or “Only Fruit”.
  • This suggests customers are increasingly placing orders that contain both food types — a cross-selling opportunity.

Exam tip: When source data is pre-aggregated (e.g., daily totals repeated per SKU), using Sum in a pivot table creates inflated values. Always check aggregation level and use Max/Min/Count if duplication exists.

Key Takeaways

  • Understand data granularity: SKU Sales Trends is daily-summary, not transactional; the second sheet is different and unrelated.
  • SKU = smallest inventory unit; classification (essentials, fruits, etc.) can be used in analysis.
  • Use set theory (AB=A+BAB|A \cup B| = |A| + |B| - |A \cap B|) to decompose overlapping categories into exclusive counts.
  • Pivot tables on pre-aggregated data require Max (or Min, Avg) instead of Sum.
  • Pivot charts with trend lines reveal growth rates; steeper slope = faster growth segment.
  • The insight “Both Veg & Fruit orders are the main growth driver” informs cross-selling strategy.

Pivot Tables – Aggregating Percentages and Week-Level Summaries

Percentages standardize quantities so you can compare across time periods or categories without being misled by raw numbers. For example, raw daily order quantities fluctuate, but converting them to percentages of total orders reveals relative trends.

Adding Percentage Columns in a Pivot Table

From the raw order data (SKU-level), create calculated columns:

  • % Both Veggies & Fruits = (Both Veggie & Fruit Orders) / Total Orders
  • % Only Veggies = (Only Veggie Orders) / Total Orders
  • % Only Fruits = (Only Fruit Orders) / Total Orders

These three sum to 100% and make trends visible. In the example, over time:

  • % Both rose from 38% → 50%
  • % Only Veggies dropped from 60% → 47%
  • % Only Fruits grew from 0% → 3%

This is far clearer than raw counts.

The Granularity Trap: Why You Cannot Reuse Day-Level Percentages for Week-Level Summaries

Directly summing or averaging daily percentages across a week produces a meaningless metric. Percentages are computed relative to the denominator of that row. At a different granularity (e.g., week), the base changes (total orders across the week vs. per day).

❌ Wrong approach✅ Correct approach
Create percentage columns at day level, then in a new pivot table sum/average those percentages per weekFirst aggregate raw numbers (total orders, veg orders, fruit orders) per week, then compute percentages from the weekly totals
Result: double-counting or mis-weighted proportionsResult: true weekly percentages

Correct Workflow for Week-Level Percentages

  1. Base data – raw daily order table (with date)
  2. Add a WeekNumber column (extracted from date using WEEKNUM())
  3. First pivot table – aggregate raw counts by week:
    • Rows: WeekNumber
    • Values (all using Max because values are identical across rows within the same week):
      • Total Orders
      • Only Veggie Orders
      • Only Fruit Orders
      • Both Veggie & Fruit Orders
    • Why Max? Each day's row already holds the daily total; we want the daily value itself, not a sum (which would sum across all days in the week incorrectly). Since it's the same value for each product within that day, Max (or Min or Average) returns the correct daily number. Then the pivot table's implicit sum across days gives the weekly total.
  4. Second pivot table (on top of the first pivot table’s data) – compute percentages:
    • Rows: WeekNumber
    • Values:
      • Total Orders (as raw number)
      • Only Veggies (sum across weeks, but we will compute % later)
      • Only Fruits
      • Both Veggies & Fruits
    • Add calculated columns:
      • % Both = Both / Total
      • % Only Veggies = Only Veggies / Total
      • % Only Fruits = Only Fruits / Total
  5. Chart – insert a pivot chart from this table to visualize week-on-week percentage trends.

Exam tip: When shifting granularity (e.g., daily → weekly), never reuse percentage fields from the finer level. Always re-aggregate the raw counts at the new level and then compute percentages. The same principle applies for any ratio metric (averages, rates, etc.).

Why Max (or Min) Works for This Aggregation

In the first pivot table (daily data, one row per product per day), each day’s total order count is the same for every product row within that day. Using Max picks that single value (or Sum would multiply it by the number of products, giving a huge inflated number). The pivot table’s row label (WeekNumber) then groups all rows in that week, and the pivot table’s implicit sum of the daily Max values gives the correct weekly total.

If you instead used Sum on the raw daily number, you would sum across all products every day, double- and triple-counting the same daily total. Always check your aggregation function matches the data’s grain.

Key takeaways

  • Percentages standardize data for trend analysis across time.
  • Granularity mismatch – do not reuse percentage fields at a coarser level; re-aggregate raw numbers first.
  • Correct hierarchy: raw data → pivot with raw counts at desired grain → new pivot with percentages.
  • Use Max (or Min, Average) when a value is identical across rows within a day to avoid double-counting.
  • Generate GetPivotData should be turned off (PivotTable Analyze → Options → uncheck “Generate GetPivotData”) when referencing cells directly in the second pivot’s calculated columns.

Pivot Tables IV: Measures and Slicers

When you add a calculated field (a column with a formula) outside a pivot table – for example, a percentage column derived from the pivot’s values – you create a static copy. If you later filter the pivot, the external formula can break (e.g., division by zero when the denominator becomes empty). The better approach: embed calculations directly inside the pivot using measures.

Drawback of External Calculations

  • External formulas reference specific cells; when the pivot reshapes (filtering, adding fields), those references may produce errors (e.g., #DIV/0!).
  • To avoid errors, you could copy the pivot as values (static), but then you lose the ability to dynamically filter or update.

Solution: Measures in Pivot Tables

A measure is a DAX (Data Analysis Expressions) formula stored inside the pivot. It recalculates automatically as the pivot changes – no errors, no stale links.

How to Add a Measure

  1. Right-click anywhere within the pivot table.
  2. Select Add Measure (or Add a Measure).
  3. Give the measure a name (e.g., % Veggie & Fruit).
  4. Write the formula using field references:
    = SUM( 'Max'[Veggie] ) + SUM( 'Max'[Fruit] ) divided by SUM( 'Max'[Total Orders] ) (or whatever aggregate is needed).
  5. Click OK – the measure appears in the Values area.

Example: Percentage Measures

From the transcript, three measures were created:

Measure NameFormulaPurpose
% Veggie & Fruit(SUM of Max[Veggie] + SUM of Max[Fruit]) / SUM of Max[Total Orders]Combined percentage of veggie + fruit orders
% Veggies OnlySUM of Max[Veggie] / SUM of Max[Total Orders]Percentage of veggie orders
% Fruits OnlySUM of Max[Fruit] / SUM of Max[Total Orders]Percentage of fruit orders

These measures can then be added to the Values area alongside or instead of raw counts. Filtering the pivot now works seamlessly – no divide‑by‑zero errors because the formula respects the current filter context.

Building Charts with Measures

  • After adding measures, create a PivotChart from the same pivot table (Insert > PivotChart, choose a line chart).
  • Remove unwanted series (e.g., raw sums) and keep only the measure fields.
  • For week-by-week analysis, place Week Number in the Rows area, not in Values.

The result: a clean line chart showing, for example, the weekly percentage distribution of veggie and fruit orders.

Exam tip: When you need to filter a pivot but also show normalized values (percentages), always use measures rather than calculated columns outside the pivot. Measures respect the filter context and prevent #DIV/0! errors.

Using Slicers for Interactive Filtering

A slicer provides a visual filter (buttons) that connects to one or more pivot tables/charts.

  • Insert a slicer from the PivotTable Analyze tab > Insert Slicer.
  • Choose the field to filter on (e.g., Week Number).
  • The slicer can be placed on a dashboard sheet.

Limitation: One Slicer per Pivot Table

A slicer can only filter pivot tables that share the same source pivot table (or the same underlying data model). If two charts come from different pivot tables (e.g., one uses Week Number, another uses Date), a single slicer cannot control both simultaneously.

  • In the transcript, two charts were created: one from a pivot that uses Week Number (measures), another from a pivot that uses Date (raw data). Trying to link the same slicer to both failed because they were not based on the same pivot.
  • To make a slicer work across multiple charts, ensure they are all derived from the same pivot table.

Practical Example: Adding Revenue Analysis

Using the same sales dataset, you can create another pivot:

  1. Insert a new pivot table (existing worksheet).
  2. Place Week Number in Rows, SKU Classification in Columns, and Sum of Revenue in Values.
  3. Insert a line PivotChart to view weekly revenue trends per product category.
  4. Optionally, add other measures like Average Sale Price or Bulk Tonnage (be careful to use the correct aggregation – e.g., AVERAGE for price).

Note: When adding multiple measures from different fields, ensure you are using the correct source pivot table to avoid mixing aggregations inconsistently. In the transcript, one attempt to add Average Price accidentally referenced a different pivot; always double‑check the source.


Key Takeaways

  • External calculations on pivot values break when the pivot is filtered – use measures instead.
  • Measures are DAX formulas stored inside the pivot; they automatically adapt to filters.
  • To build a chart with percentages, create a measure (e.g., % Veggies = SUM(Veggies)/SUM(Total)) and use it in a PivotChart.
  • Slicers provide interactive filtering but only work across charts that share the same pivot table.
  • To avoid filtering issues, design all charts from one pivot table or use a common data model (Power Pivot) for cross‑chart slicers.

Pivot Tables for Dashboard Creation

A dashboard pulls together multiple visualisations that share a common data source and allows interactive filtering through slicers. The key is to build a master pivot table that contains all the necessary fields (dates, categories, metrics) at the lowest granularity, then create derived pivot charts that each show a different metric. A single slicer can then filter all charts simultaneously.

Building a Master Pivot Table

Start with the raw data table. Insert a new pivot table and add rows or columns to define the granularity – the level at which each metric will be shown. A good granularity for time‑series analysis is Date (or Week Number) combined with SKU Classification (or SKU Name).

FieldRoleExample
DateRow (daily)2025-01-07
Week NumberRow (derived from date)Week 1
SKU ClassificationRow (category)Fruits
Sale PriceValue – use Max (single value per day)45.00
RevenueValue – use Sum (aggregated per day)12,500
Built TonnageValue – use Sum2,300
Return TonnageValue – use Max (same as sum at lowest level)76

Why Max for Sale Price? At the lowest level (one date + one SKU) there is only one price per day. Using Max avoids summing duplicate entries that may appear from the raw data. For aggregated totals (e.g., revenue, tonnage) use Sum.

After adding fields, tidy the pivot table layout:

  • Design tab → Subtotals → Off
  • Grand Totals → Off
  • Report Layout → Show in Tabular Form
  • Repeat All Item Labels

This gives a clean, row‑by‑row table where every date and category appears explicitly.

Creating Linked Charts

From the master pivot table, create three separate pivot charts (line charts are typical for trends), each using the same master table as its data source. The row fields (Date, Week, SKU Classification) stay the same; only the value field changes.

ChartValue FieldExample Interpretation
Tonnage TrendSum of Built TonnageVolume moving through time
Price TrendMax of Sale PriceUnit price evolution
Revenue TrendSum of RevenueTotal income – product of price × tonnage

To create a chart: select the master pivot table → InsertPivot ChartLine. In the PivotChart Fields pane, remove the previous value field and add the desired one.

Adding Interactivity with a Slicer

Add one slicer (e.g., on SKU Classification) and connect it to all pivot tables that feed the charts.

  1. Click on any pivot chart or table → InsertSlicer → choose SKU Classification.
  2. Right‑click the slicer → Report Connections and tick every pivot table (master table plus the three chart‑specific ones).
  3. The slicer now filters all charts simultaneously.
flowchart LR
  A[Master Pivot Table] --> B[Tonnage Chart]
  A --> C[Price Chart]
  A --> D[Revenue Chart]
  E[SKU Classification Slicer] --> B
  E --> C
  E --> D

Arrange the three charts side‑by‑side on a dedicated dashboard sheet. The slicer sits next to them for easy filtering.

Example Dashboard Analysis

After filtering for Fruits, a manager observes:

  • Sale Price decreased week on week
  • Tonnage increased steadily then sharply dropped in week 9
  • Revenue rose initially, then crashed when tonnage fell

Such side‑by‑side comparison reveals cause‑effect relationships (e.g., price cuts may have driven volume until a disruption occurred). The same logic applies to other categories like Onion, Potato, Tomato.

Exam tip: The master pivot table approach avoids duplicating slicers and ensures all charts stay in sync. Remember to set numeric fields to the correct aggregation (Max for unique values, Sum for totals) at the chosen granularity.

Key takeaways

  • Build one master pivot table with all needed dimensions (date, week, SKU) and metrics (price, revenue, tonnage).
  • Use Max for fields that have a single value per row (e.g., sale price) and Sum for aggregated totals.
  • Create separate pivot charts for each metric, all sourced from the same master table.
  • Add a single slicer and link it to every pivot table in the dashboard.
  • Side‑by‑side charts enable instant comparison of trends and help identify relationships between price, volume, and revenue.

Dashboard Creation with Pivot Tables and Slicers

A dashboard consolidates multiple visualizations linked by a common filter. Pivot tables feed pivot charts, and slicers enable interactive filtering across all charts derived from the same base table.

Constructing a Master Pivot Table

To manage multiple views efficiently, create one master pivot table containing all necessary fields aggregated at the desired granularity (e.g., week level). From this master, generate separate smaller pivot tables for individual charts.

Steps:

  1. Insert a pivot table from the raw data, adding it to the data model for advanced calculations.
  2. Place fields: row labels (e.g., week number), values (e.g., max of total orders, max of percentage veggies, max of percentage fruits).
  3. Set value field settings to appropriate aggregation – max for daily totals (to avoid double-counting when aggregating by week), average for percentages.
  4. Remove subtotals and grand totals, apply a tabular layout for clarity.

Example fields in master pivot:

RowValue 1Value 2Value 3
Week 1Max(Total Orders)Avg(% Veggies)Avg(% Fruits)
Week 2.........

Creating Linked Charts from Sub-Pivots

Insert new pivot tables using the master pivot’s range as source. This ensures all sub-pivots share the same underlying data.

  • Sub-pivot 1: Week number → Max(Total Orders) – line chart for order volume trend.
  • Sub-pivot 2: Week number → Avg(% Veggies), Avg(% Fruits), Avg(% Both) – line chart for order mix distribution.

Exam tip: When using percentages, aggregate by average per week, not sum. Summing percentages across weeks is meaningless.

Adding Slicers and Linking Across Charts

Insert a slicer on a common field (e.g., week number). To link it to multiple pivot charts:

  • Right-click the slicer → Report Connections – select all charts that should respond.
  • All pivots must originate from the same base table (or the same master pivot) for the slicer to filter them simultaneously.
flowchart TD
    A[Raw Data Table] --> B[Master Pivot Table]
    B --> C[Sub-Pivot 1: Orders Trend]
    B --> D[Sub-Pivot 2: Order Mix]
    B --> E[Sub-Pivot 3: Price/Volume/Revenue]
    F[Slicer (Week)] --connects to--> C
    F --connects to--> D
    F --connects to--> E

Analyzing Price–Volume–Revenue Interactions

By combining slicers with pivot tables showing price, tonnage (quantity), and revenue, a manager can spot anomalies. Key observations from the lecture (applied to SKUs like Tomato, Potato, Onion, Fruits, Essentials):

SKUPrice TrendTonnage TrendRevenue Outcome
TomatoSlight drop (₹10→₹6→₹8)Massively increasedIncreased slightly
PotatoStable (₹~same)IncreasedIncreased
OnionDropped sharply (₹45→₹20)Increased initially, later flatIncreased then decreased
FruitsDropped slightly (₹50→₹40)Increased 4×Increased ~3×
EssentialsCrashed (₹70→₹30)DoubledLanguished (flat)

Lesson: Revenue =Price×Quantity= \text{Price} \times \text{Quantity}. A price drop can offset volume gains, leading to flat or falling revenue. Slicers allow zooming into specific time windows to isolate such dynamics.

Key Takeaways

  • Build a master pivot at the desired aggregation level (e.g., week) to serve as a single source for multiple charts.
  • Use average for percentage fields when aggregating over time; use max to avoid summing daily totals.
  • Slicers filter all connected pivot charts simultaneously only if those pivots share the same base data range.
  • Price–volume–revenue analysis reveals whether revenue follows tonnage or gets eroded by price declines.
  • Dashboard interactivity enables managers to drill into specific periods (e.g., 4 weeks) and compare trends across SKUs or categories.

Pivot Tables – VII: Customer & Regional Segmentation

Customer-level data (sales, customer, SKU) with 50,000 rows can reveal powerful insights when summarized with PivotTables and simple formulas. The goal is to segment customers and regions without charts, using only PivotTable summaries and IFS logic.


Extracting Customer Metrics

Create a PivotTable with Customer ID in rows and the following measures (all as summed values unless noted):

MeasurePivotTable FieldAggregationPurpose
Total Build ValueBuild ValueSumRevenue per customer
Return QuantityReturn QTYSumAbsolute returns
Build QuantityBuild QTYSumVolume ordered
Unique SKUsSKU IDDistinct CountProduct variety per customer
Order FrequencyDate (Delivery Date)Distinct CountHow many times they ordered in the month

These raw measures are then used to compute derived metrics:

  • Return % = Sum (Return QTY) / Sum (Build QTY)
  • Average Order Value (Ticket Size) = Sum (Build Value) / Count of Delivery Date

Exam tip: Adding a measure directly inside the PivotTable (e.g., using Value Field Settings > Show Values As or a calculated field) keeps the analysis dynamic. The transcript uses a separate column with =IFS(...) formulas referencing the PivotTable output.


Customer Segmentation with Formulas

Once the PivotTable is built, segment customers by adding helper columns with IFS (or nested IF) formulas.

Value Category (based on Total Build Value)

ConditionCategory
> 200,000Category 1
> 100,000Category 2
> 50,000Category 3
≤ 50,000Category 4
=IFS( [@[Sum of Build Value]] > 200000, "Category 1",
      [@[Sum of Build Value]] > 100000, "Category 2",
      [@[Sum of Build Value]] > 50000, "Category 3",
      TRUE, "Category 4")

Handle blanks by converting to zero (e.g., with IF or IFERROR).

Return Nature (based on Return %)

Return %Category
> 10%High Return (bad)
> 4%Medium Return
≤ 4%Low Return (good)

Frequency (based on Distinct Order Count per month)

Days OrderedCategory
> 20High Frequency
> 10Medium Frequency
≤ 10Low Frequency

Exam tip: The same logic can be extended to Average Order Value — high ticket size is desirable even if order count is low.


Regional Analysis (Same PivotTable, Different Row Field)

Replace Customer ID with Locality Cluster to see aggregated regional performance.

MetricHow to get it
Total Build Value per localitySum of Build Value
Return %Sum(Return QTY)/Sum(Build QTY)
Number of ordersCount of Delivery Date (not distinct, as each row is a transaction)
Average Order ValueSum(Build Value) / Count of DD
  • Sorting by Build Value (descending) immediately reveals top regions.
  • Example insight: JP Nagar and Nagarbhavi (south-west Bangalore) are most valuable; Yeswanthpur underperforms, possibly due to competition (APMCR).
flowchart LR
    A[PivotTable Row: Locality] --> B[Add Measures]
    B --> C[Sort by Total Build Value]
    C --> D{Top region?}
    D -->|JP Nagar| E[Highest revenue & order value]
    D -->|Yeswanthpur| F[Low revenue – investigate]

Key Takeaways

  • PivotTables alone (without charts) can yield actionable insights for managers — summary in 8 rows instead of 50,000.
  • Derived metrics (return %, average order value) are critical for segmentation.
  • Formulas (IFS) convert raw PivotTable outputs into meaningful customer tiers (value, return nature, frequency).
  • Regional analysis follows the same pattern: replace the row field and apply the same measures and sorting.
  • Segments drive action – high value + high frequency customers get offers; high return customers need investigation.
  • Always handle empty cells in PivotTable outputs (e.g., force 0 for blank build value).

Data Insights and Dashboard Creation

Module 2 transformed raw transaction logs into a live decision tool – a manager's cockpit that consolidates key metrics into a single interactive view. Instead of static spreadsheets, you now have a system that answers: Who are my most valuable customers? Which area returns the most? How do revenues shift with price and volume?

A manager's cockpit is a dashboard that consolidates key metrics into one interactive view, allowing on-demand drill-down and slicing.

What We Built

  • Pivot Tables – Clean, aggregated summaries from raw data (daily sales trends, SKU-level order patterns, geographic breakdowns).
  • Dynamic Pivot Charts – Visual representations of business movements (e.g., revenue trends, volume shifts) that update automatically when underlying data changes.
  • Interactive Dashboards – A collection of pivot charts bound together with slicers and filters so users can slice data instantly (e.g., filter by region, time period, product category).
  • Customer Segmentation – Logical rules and thresholds applied to segment customers (e.g., by geography or value). Segments are defined using decision logic – for example, high-value customers meet threshold conditions on revenue, frequency, or recency.

Components of the Dashboard

ComponentFunctionExample in Context
Pivot TableAggregate raw data into summariesDaily sales totals, SKU-level order volume
Dynamic Pivot ChartVisualize business movementsLine chart of revenue over time, bar chart of regional sales
Slicer / FilterBuild interactivity – slice data instantlySelect a region → all charts update to show that region
DashboardSingle pane for key metricsDisplays customer segmentation, geographic performance, revenue & volume trends

Process: Raw Data to Dashboard

flowchart LR
  A[Raw Transaction Data] --> B[Pivot Tables]
  B --> C[Pivot Charts]
  C --> D[Dashboard with Slicers & Filters]
  D --> E{Insights}
  E --> F[Customer Segmentation<br>by Logic / Thresholds]
  E --> G[Geographic Performance<br>Most returns by area]
  E --> H[Revenue & Volume<br>Changes w.r.t. price & quantity]

Insights Unlocked

  • Most valuable customers – Who contributes the most revenue or frequency? Segments are revealed by logical thresholds.
  • Best-performing areas – Which geography brings the highest returns? Geographic segmentation isolates top regions.
  • Revenue vs. price and volume – How do revenues change when price moves or volume shifts? The dashboard surfaces trends and correlations.
  • Behavioral interpretation – Beyond numbers: identifying gaps, surfacing growth opportunities, and understanding why patterns occur.

Exam tip: Segmentation by geography and logic is covered here. Behavioral segmentation (RFM – recency, frequency, monetary) appears in Module 3. Do not confuse the two; RFM uses weighted scores, not simple thresholds.

Key Takeaways

  • Module 2 built a manager's cockpit from raw data using pivot tables, charts, slicers, and filters.
  • Customer segmentation relies on logical rules and thresholds (e.g., geography, value thresholds).
  • Dynamic dashboards answer: most valuable customers, best regions, revenue–volume–price relationships.
  • The focus is on structured business dashboards – not advanced analytics (that comes in Module 3 with CLV, cohort analysis, RFM, and clustering).

Intermediate Excel and Google Sheets with App Scripts

Introduction to ERP Systems and Spreadsheets

ERP (Enterprise Resource Planning) is the central nervous system of a business – it connects departments (sales, finance, operations, HR, inventory, procurement) so everyone works from a common set of data.

<!-- Intuition: Without an ERP, each department keeps its own records, causing delays, errors, and inefficiencies. An ERP streamlines processes and provides real-time data for better decisions. -->
Why ERP?What happens without itWith ERP
Department silosSales, inventory, finance each maintain separate recordsSingle source of truth
Data delays & errorsReconciliation is manual, slow, error-proneReal-time updates & automated checks
Poor decisionsDecisions based on stale or inconsistent infoDecisions backed by live, cross‑department data

Popular ERPs in India

  • Global: SAP, Oracle, NetSuite, Microsoft Dynamics
  • Indian: Tally, Zoho, Odoo, ERP Next
  • Large enterprises (Infosys, Tata Steel, Mahindra) use full‑fledged ERPs; many SMEs use modular systems (Tally, Zoho) or self‑built spreadsheets.

Core ERP Modules

ModulePurpose
Customer management (CRM)Track interactions, leads, customer relationships
Inventory managementMonitor stock levels, movements, availability
Purchase & vendor managementHandle procurement cycles, purchase orders, vendor performance
Finance & accountingBilling, payments, financial reporting, compliance
HR & payrollEmployee records, attendance, salary, benefits
Operations & production planningPlan/track production workflows, allocate resources

The Real‑World Role of Spreadsheets

Even large enterprises rely on spreadsheets alongside ERPs. In 2025, over 71% of large enterprises globally still use Excel or Google Sheets for critical financial and operational analysis. In India, giants and startups alike use spreadsheets for:

  • Reporting & reconciliation
  • Quick analysis
  • Custom operations

Spreadsheets are the bridge between formal ERP systems and human flexibility.

What This Module Covers

We will treat spreadsheets as data capture and processing tools – like a mini‑ERP. The module builds toward creating your own mini‑ERP.

  1. Linking sheetsVLOOKUP, INDEX+MATCH, dynamic referencing
  2. Logical functionsIF, AND, OR for decision‑making in sheets
  3. Delivery fee calculator – a real‑life logistics calculator
  4. Google Forms – capture user input directly into sheets (field teams, customer feedback, order management)
  5. Google Apps Script – automate repetitive tasks, link external APIs, turn static sheets into live business systems

Exam tip: Spreadsheets are not a crutch – they are a fundamental tool even in ERP‑heavy enterprises. Understanding how to use them as a mini‑ERP (linking tables, automating logic) is a skill tested in many business‑analyst interviews.

Key takeaways

  • ERP unifies departments with real‑time, shared data.
  • Common modules: CRM, inventory, procurement, finance, HR, production.
  • Spreadsheets are still used by >70% of large enterprises for critical work – they bridge ERP rigidity with human flexibility.
  • This module transforms spreadsheets into a mini‑ERP using lookup functions, logical formulas, Google Forms, and App Script.

Data Linking Across Sheets

Data linking turns separate spreadsheet tables into a connected system — a lightweight ERP. By linking master data (products, customers) to transaction sheets, you avoid manual lookups, reduce errors, and enable real‑time calculations.

Context: A wholesale vegetable delivery company operates in Bangalore, Chennai, and Mumbai. Orders come via phone, form, or app. The goal is to quickly calculate order costs and delivery fees using linked sheets.

Product Master: Structure and Auto‑Generation

A product master stores the core product catalogue. It’s a dedicated sheet with columns:

ColumnExample Data
Product CodeP0001
Product NameTomato
Price (₹/kg)50
On‑hand Quantity200

Product Code is the primary key — a unique identifier that prevents errors from name variations (spacing, case). Always link tables using codes, not names.

Automatic Code Generation with Text Formulas

Instead of typing codes manually, use a formula that auto‑increments when a product row is added.

=IF(B2<>"", "P" & TEXT(ROW(B2)-1, "0000"), "")

How it works:

  • IF(B2<>"", … , "") — only generate a code if the product name (B2) is non‑empty.
  • ROW(B2) returns the current row number (2 in this example). Subtract 1 to start from 1.
  • TEXT(ROW(B2)-1, "0000") formats the number as a 4‑digit zero‑padded string (1"0001").
  • Concatenate "P" with the formatted number → "P0001".

Copy the formula down the column. When you insert or delete rows, the codes update automatically.

Exam tip: Always use a unique, system‑generated key (like P0001) instead of manual numbering. It survives row insertions and deletions.

Protecting Master Data

Prevent accidental edits to the product master by protecting the range.

  1. Select the range containing the master data.
  2. Go to Data > Protect ranges (or Review > Protect Sheet in Excel).
  3. Set permissions so that only authorised users (e.g., you) can edit.

This keeps the master data clean and reliable for all linked sheets.

Customer Master: Structure and Email Uniqueness

A customer master stores customer details. Columns:

ColumnExample
Customer IDC0001
NameKavita Foster
CityBangalore
Subscription TypePremium
Emailkfoster@bender.com

Customer IDs are generated the same way as product codes, using "C" instead of "P":

=IF(B2<>"", "C" & TEXT(ROW(B2)-1, "0000"), "")

Enforcing Unique Emails with Data Validation

To prevent duplicate customer registrations, add a data validation rule on the email column.

  1. Select the email range (e.g., E2:E).
  2. Go to Data > Data validation.
  3. Set Criteria to Custom formula is.
  4. Enter the following formula:
=COUNTIF($E$2:E, E2) = 1

What it does:

  • COUNTIF($E$2:E, E2) counts how many times the email in the current cell (E2, E3, …) appears in the entire column (from E2 downwards).
  • The formula returns TRUE only when the count equals 1 (i.e., the email is unique).
  • If the user tries to enter a duplicate email, the validation rejects the input.

Referencing note: The $E$2:E uses a mixed reference — the start of the range is locked ($E$2), but the end is relative (E), so as the rule applies to each cell, the range stays anchored to the top while the value being checked moves.

Exam tip: In data validation custom formulas, use mixed references ($ for the start) to keep the lookup range fixed while checking each row’s value.

Key Takeaways

  • Linking sheets with unique codes (product code, customer ID) is the foundation of a spreadsheet‑based mini‑ERP.
  • Auto‑generate codes using IF, TEXT, and ROW to avoid manual errors and handle row insertions.
  • Protect master data ranges to prevent accidental edits.
  • Enforce data integrity with data validation — e.g., =COUNTIF($E$2:E, E2)=1 ensures unique emails.
  • Use mixed references ($E$2:E) to lock the start of a range while allowing the checked cell to move.

Data Linking using Spreadsheets – II

Building an order sheet with a calculation system. The goal: capture orders by selecting Customer ID and Product ID from validated lists, then automatically populate related fields (names, city, product name). This prevents manual entry errors and keeps data structured.

Data Validation for Dropdowns

Restrict inputs to valid IDs using dropdowns from a source range.

  • Select the column (e.g., Customer ID).
  • Data → Data validation → Add rule (Google Sheets) or Data Validation (Excel).
  • Choose Dropdown from a range, then point to the ID column in the master sheet.
  • Use absolute referencing ($A$1:$A$1000) so the range stays fixed when copied.
  • Remove the $ on the last row (e.g., $A$1:$A) to make the range "infinite" (Google Sheets).

Apply a second validation for Product ID similarly.

Exam tip: Always use absolute referencing ($) for the lookup range in data validation when you intend to copy the validation down. Without $, the range shifts and breaks.

VLOOKUP for Single‑Row Lookups

VLOOKUP searches the first column of a table, moves horizontally to a specified column, and returns the corresponding value.

Syntax: =VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])

  • lookup_value: the ID to match (e.g., A2).
  • table_array: the master data range (absolute, e.g., $A$1:$E$1000).
  • col_index_num: the column number in the range (1‑based: 1 = first column, 2 = second, etc.).
  • range_lookup: FALSE for exact match (always use for IDs).

Example – fill Customer Name
=VLOOKUP(A2, CustomerMaster!$A$1:$E$1000, 2, FALSE)

  • A2 = chosen Customer ID.
  • CustomerMaster!$A$1:$E$1000 = master table (absolute).
  • 2 = second column contains the name.

Copy down – the A2 reference changes (relative), but the table array stays fixed because of $.

Absolute vs. Relative Referencing

ReferencingSyntaxBehaviour when copied
Absolute$A$1Does not change – locks to that cell.
RelativeA1Adjusts by row/column offset.
Mixed$A1 or A$1Only one part fixed.

Shortcut: F4 (Windows) to toggle through absolute/relative modes.

Handling Missing Data – IFERROR

When no customer is selected, VLOOKUP returns #N/A. Wrap the formula in IFERROR to output a blank instead:

=IFERROR(VLOOKUP(...), "")

Apply the same pattern for city (col 3), product name, etc., referencing the appropriate master sheet and column index.

INDEX‑MATCH – Two‑Dimensional Lookups

INDEX‑MATCH is more flexible than VLOOKUP: it can look up values in any direction and handle two‑way lookups (row + column).

INDEX

=INDEX(reference, row_num, [column_num])
Returns the value at the intersection of a given row and column within reference.

MATCH

=MATCH(lookup_value, lookup_array, [match_type])
Returns the relative position of lookup_value in lookup_array (1‑based).
Use 0 for exact match.

Combined

Replace row_num and column_num in INDEX with MATCH functions to dynamically find the correct row and column.

Workflow:

flowchart LR
    A[Lookup Value] --> B[MATCH → row index]
    C[Column Header] --> D[MATCH → column index]
    B & D --> E[INDEX(data, row, col) → result]

Example – delivery fee based on city and weight slab

Weight SlabBLRCHNMUN
<5 kg304050
5–10 kg506070
10–25 kg100120140
25–100 kg150200220
>100 kg250300350

To get the fee for city "CHN" and slab "10–25 kg":

  • MATCH("CHN", city_header_row, 0) → column index 3.
  • MATCH("10–25 kg", weight_slab_column, 0) → row index 4.
  • INDEX(fee_table, row_index, col_index) → returns 120.

This works even if the lookup columns are not the leftmost (unlike VLOOKUP).

Key takeaways

  • Data validation restricts inputs; always use absolute ranges when copying.
  • VLOOKUP is simple for left‑to‑right lookups; set FALSE for exact match.
  • IFERROR cleans up #N/A when no input is given.
  • INDEX‑MATCH enables two‑dimensional lookups and is not limited to the first column.
  • Absolute referencing ($) is critical for ranges that must not shift; use F4 to toggle.
  • Automating lookups reduces manual entry errors (spelling, case, spacing).

Building a Delivery Fee Calculator

The goal is a calculator that takes city, quantity (kg), and product as inputs and outputs the final price (product cost + delivery fee). This mimics a mini-ERP system where data is linked across sheets.

Core components:

  • Data validation for city (BLR, CHN, MUM), product (from product master), and customer (from customer master).
  • Quantity slab – map a numeric quantity into a pre-defined weight range using IFS.
  • Pricing table – lookup delivery fee based on city and slab using INDEX-MATCH.
  • Product master – lookup price per kg using VLOOKUP.
  • Final formula:
    \text{final_price} = (\text{price_per_kg} \times \text{quantity}) + \text{delivery_fee}

Using IFS for Quantity Slabs

IFS evaluates conditions sequentially – the first true condition returns its value.
No need to check both lower and upper bounds; the order guarantees the correct range.

Example:

=IFS(
  A1<5, "Less than 5 kg",
  A1<10, "5 to 10 kg",
  A1<25, "10 to 25 kg",
  A1<100, "25 to 100 kg",
  TRUE, "Above 100 kg"
)
  • If quantity = 10, condition A1<10 is false (since 10 is not less than 10), so it falls to A1<25 → "10 to 25 kg".
  • If quantity = 9.9, A1<10 is true → "5 to 10 kg".

Exam tip: IFS stops at the first true condition. Always place narrower ranges first. Use TRUE as a catch-all final condition.

INDEX-MATCH for Two-Way Lookup

To retrieve the delivery fee from a pricing table where rows = city and columns = quantity slab:

  • Row match: MATCH(city, city_range, 0)
  • Column match: MATCH(slab, slab_range, 0)
  • INDEX: INDEX(fee_range, row_num, col_num)

Worked example (from lecture data):

City<5 kg5–10 kg10–25 kg25–100 kg
BLR............
CHN......120...
MUM......140...
  • Quantity = 23 kg → slab = "10 to 25 kg". City = CHN.
  • Row match on CHN → row 2; column match on "10 to 25 kg" → column 3.
  • INDEX returns 120.

Always use exact match (0 or FALSE) in MATCH for pricing lookups.

VLOOKUP for Product Price per kg

From the product master table (columns: Product Name, Price per kg):

=VLOOKUP(product_name, product_master, 2, FALSE)
  • Use product codes instead of names in production to avoid duplicates.

Adding Subscription Logic with IF, AND

Enhance the calculator: if the customer is free, use the standard delivery fee (from INDEX-MATCH). If premium, apply a flat rate per city regardless of weight.

Steps:

  1. VLOOKUP customer → subscription type (free / premium).
  2. Use IFS with AND:
    =IFS(
      subscription_type = "free", standard_delivery_fee,
      AND(subscription_type = "premium", city = "BLR"), 30,
      AND(subscription_type = "premium", city = "CHN"), 50,
      AND(subscription_type = "premium", city = "MUM"), 70
    )
    
  3. The AND function returns TRUE only if all conditions are true.
Logical FunctionBehavior
AND(cond1, cond2, ...)TRUE if all conditions TRUE
OR(cond1, cond2, ...)TRUE if any condition TRUE
NOT(cond)Flips TRUE ↔ FALSE
SWITCH(expr, case1, val1, case2, val2, ...)Match expression (Excel 2026+)

Final calculator structure (user inputs only yellow cells):

  • Customer (dropdown) → auto-populates city and subscription type via VLOOKUP.
  • Product (dropdown) → auto-populates price per kg via VLOOKUP.
  • Quantity (manual) → determines slab → delivery fee via INDEX-MATCH (then overridden by premium logic if needed).
  • Final price = price_per_kg * quantity + delivery_fee_final

Exam tip: Use nested IF or IFS for multi-condition branching. AND/OR reduce nesting and improve readability.

Key Takeaways

  • IFS evaluates conditions sequentially; use TRUE as a default.
  • INDEX-MATCH performs two-dimensional lookups (row + column) without restructuring data.
  • VLOOKUP is simpler for single-column lookups; prefer product codes over names.
  • Combine IF/IFS with AND to implement conditional business rules (e.g., premium flat rate by city).
  • Build a clean user interface: hide helper columns, mark input cells in yellow.
  • All formulas can reference data from other sheets, creating an interconnected system that simulates an ERP.

Capturing Data using Google Forms

Google Forms integrated with Google Sheets provides a structured way to capture data from external users (e.g., sales or inventory teams) directly into a spreadsheet. Rather than manually entering data into a sheet, a form enforces consistency, reduces errors, and automatically timestamps entries. This feature is unique to Google Sheets and is not available in Excel (which requires custom VBA forms).

Creating a form from within a sheet links the responses to a dedicated sheet tab; every new submission appends a row instantly.

Creating a form from Sheets

  • Go to Tools → Create a new form (or use the Forms menu in Sheets).
  • The form is automatically linked to a new sheet tab named “Form Responses 1”.
  • Rename the form and the response tab (e.g., “Inventory Purchase Form”).

Designing the form questions

  • Dropdown question – predefined choices (e.g., product names). Useful for standardised data.
  • Short answer – free text; apply a validation rule (e.g., number > 0) to enforce quality.
  • Timestamp – added automatically by the form (not a question).

Exam tip: Always validate numeric fields (number > 0) to prevent invalid entries. Forms with validation are significantly more reliable than raw sheet input.

Publishing and collecting responses

  • Click Publish → a responder link is generated.
  • Anyone with the link can fill the form; each submission appends a row to the linked sheet.

Automatic logging in the sheet

  • The response sheet logs: Timestamp, and each question’s answer as columns.
  • Data can be immediately used for analysis (e.g., inventory purchases linked to product master).
flowchart LR
  A[Team member fills form] --> B[Google Form]
  B --> C[Linked Sheet tab]
  C --> D[Inventory analysis]

Excel vs. Google Sheets

FeatureGoogle SheetsExcel (desktop)
Native form integrationBuilt-in via Google FormsNo native equivalent – requires VBA UserForms or Power Apps
Automatic response loggingAutomatically appends rows to sheetManual macro / Power Query needed
Real-time collaborationMultiple users submit, instant updateNo real-time

Key takeaways

  • Google Forms provide a controlled, structured input method for Sheets – ideal for teams.
  • Create a form from Tools → Create a new form; it auto-links to a response sheet.
  • Use dropdown for fixed options and short answer with validation for numeric fields.
  • Timestamps are captured automatically.
  • Forms are a Google Sheets-only advantage over desktop Excel.
  • The logged data (e.g., inventory purchases) can be linked to other sheets for further analysis (e.g., reorder level calculations).

Lead Time

Lead time is the time between placing an order and receiving the goods. It is a critical input for inventory planning: knowing how long replenishment takes determines when to reorder.

  • Average lead time: the typical number of days from order to delivery (e.g., tomatoes and potatoes usually arrive in 2 days, oranges in 5 days).
  • Max lead time: the longest possible delay (e.g., from an unreliable supplier). Used to manage risk – even if most orders arrive on time, a safety buffer is needed for late deliveries.

Both values are derived from historical data, supplier agreements, or experience. In the sample data:

ProductAverage Lead Time (days)Max Lead Time (days)
Tomato2(known from data)
Potato2
Orange5

Key takeaway: Lead time drives reorder timing; max lead time builds a risk cushion.


On-Hand Inventory

The quantity of each product currently in stock. Combined with lead time and expected sales, it determines when and how much to reorder.

  • If inventory is low and lead time is long, a reorder must be placed earlier.
  • On-hand inventory is a direct input for reorder point calculations.

Average Daily Sales

Average daily sales estimates how many units of a product are sold per day. This is used to forecast how much inventory will be consumed during the lead time.

Calculation method: Use a pivot table on the order master to first sum daily quantities per product, then average those daily totals.

Step 1: Build a pivot table that sums order quantities per product per day

  • Row fields: Product ID and Product Name (with repeat row labels), and Purchase Date.
  • Value field: Order Quantity, summarized by Sum.
  • Result: for each product and each date, the total kgs sold that day.

Common mistake: Directly averaging order quantities gives the average order size, not average daily sales. Summing daily totals first corrects for multiple orders on the same day.

Step 2: Create a second pivot table on the first pivot table to compute average and standard deviation

  • Row fields: Product ID and Product Name (filter blanks).
  • Value fields:
    • Average of Sum of Order Quantity → average daily sales.
    • Standard Deviation of Sum of Order Quantity → measure of daily fluctuation.

Data flow:

flowchart LR
    A[Order Master<br/>(raw transactions)] --> B[Pivot Table 1<br/>Sum of quantity per product per date]
    B --> C[Pivot Table 2<br/>Average and Std Dev of daily totals]
    C --> D[Average Daily Sales<br/>and Std Dev]

Formally:

Let Qp,dQ_{p,d} be the sum of order quantities for product pp on day dd (from Step 1). Then for nn days:

Average Daily Salesp=1ndQp,d\text{Average Daily Sales}_p = \frac{1}{n}\sum_{d} Q_{p,d} Std Dev (sample)p=1n1d(Qp,dAvgp)2\text{Std Dev (sample)}_p = \sqrt{\frac{1}{n-1}\sum_{d} \left(Q_{p,d} - \text{Avg}_p\right)^2}

Exam tip: Always ask: "What does the average represent?" The pivot table's average of raw order quantities is not average daily sales – it's the average order size. You must aggregate by day first.


Standard Deviation of Daily Sales

Standard deviation captures the fluctuation (inconsistency) of daily sales. A higher standard deviation means sales vary more from day to day.

  • More fluctuation → need a larger buffer inventory (safety stock) to avoid stockouts on unexpectedly high sales days.
  • Higher average daily sales also require more inventory because items move faster.

Key relationship:

  • Average daily sales → base stock needed for lead time.
  • Standard deviation → safety stock to cover variability.

Key takeaway: Use both average and standard deviation of daily sales to set inventory levels – not just the average alone.


Key takeaways for Concepts in Spreadsheets – I

  • Lead time (average & max) drives reorder timing and risk management.
  • On-hand inventory is the starting point for reorder decisions.
  • Average daily sales must be computed as the average of daily sums, not of raw orders.
  • Standard deviation of daily sales quantifies demand variability and determines safety stock.
  • Pivot tables on pivot tables enable this two‑step aggregation.

Enhancing the Product Master with Sales Statistics

To compute inventory metrics, the product master table is extended with two derived fields from daily sales data:

  • Average daily orders – obtained via a pivot table (grouping by product key) and then pulled into the master with =VLOOKUP(product_key, pivot_table_range, column_index, FALSE).
  • Standard deviation of daily orders – same pivot approach, but selecting the STDEV.P (or STDEV.S) aggregation. The formula is copied across after anchoring the lookup range with absolute references (e.g., $A$1:$C$100).
MetricSourceCalculation
Average daily ordersPivot (AVERAGE)=VLOOKUP(key, pivots!A:C, 3, FALSE)
Std dev of daily ordersPivot (STDEV)=VLOOKUP(key, pivots!A:C, 4, FALSE)

Jackfruit example: average daily order = 12, standard deviation is high because order quantities in the source data include 50 and 25 – orders fluctuate significantly.

Why Safety Stock Is Necessary

Inventory faces two independent sources of uncertainty:

  1. Demand fluctuation – daily orders vary around the average.
  2. Supply lead time fluctuation – the time between placing an order and receiving it is not constant (e.g., average 2 days, max 5 days).

Without a buffer, a spike in demand or a delay in supply causes a stockout – inability to fulfil orders.

Safety Stock: A Rudimentary Calculation

Safety stock is the minimum inventory kept to absorb worst‑case scenarios.

Approach 1: Simple range method (illustrative)

Safety Stock=(Max Lead TimeAvg Lead Time)×(Max Daily OrdersAvg Daily Orders)\text{Safety Stock} = (\text{Max Lead Time} - \text{Avg Lead Time}) \times (\text{Max Daily Orders} - \text{Avg Daily Orders})

This covers the case where both extremes happen simultaneously.

Approach 2: Using standard deviation (practical)

Since we have only the average and standard deviation of daily orders, we approximate the “max” as Avg+2σ\text{Avg} + 2\sigma (covering ~95% of demand if normally distributed). Then:

Safety Stock=(Max Lead TimeAvg Lead Time)×2σdaily orders\text{Safety Stock} = (\text{Max Lead Time} - \text{Avg Lead Time}) \times 2\sigma_{\text{daily orders}}

Why 2σ? In a normal distribution, the average ± 2σ contains about 95% of all values. This corresponds to a 95% service level – you will have enough stock 95% of the time.

The transcript notes this is a rudimentary method; professional settings use joint distributions of lead time and demand variability.

Reorder Point (ROP)

The reorder point is the inventory level at which a new order should be placed. It consists of two parts:

  • Safety stock – always kept for worst‑case events.
  • Cycle stock – quantity needed to cover average demand during the average lead time.

Reorder Point=Safety Stock+(Average Daily Orders×Average Lead Time)\text{Reorder Point} = \text{Safety Stock} + (\text{Average Daily Orders} \times \text{Average Lead Time})

When physical stock falls to this level, a replenishment order is triggered.

Worked Example (Illustrative)

Assume:

  • Average daily orders = 12 units
  • Std dev of daily orders = 5 units
  • Average lead time = 2 days
  • Max lead time = 5 days

Safety stock (using 2σ method): Safety Stock=(52)×(2×5)=3×10=30 units\text{Safety Stock} = (5 - 2) \times (2 \times 5) = 3 \times 10 = 30 \text{ units}

Reorder point: ROP=30+(12×2)=30+24=54 units\text{ROP} = 30 + (12 \times 2) = 30 + 24 = 54 \text{ units}

Interpretation: When on‑hand inventory reaches 54 units, place a new order. The 30 units of safety stock will only be used if demand is unusually high or lead time is extended.

Inventory Decision Logic

flowchart TD
    A[Monitor inventory] --> B{Stock ≤ Reorder Point?}
    B -->|No| A
    B -->|Yes| C[Place order for replenishment]
    C --> D[Wait during lead time]
    D --> E[Receive goods]
    E --> A

The safety stock ensures that during the lead time, even if demand surges or the shipment is delayed, the inventory does not hit zero.

Key takeaways

  • Use VLOOKUP and pivot tables to compute average and std dev of daily orders per product.
  • Safety stock = (max lead time – avg lead time) × 2 × std dev of daily orders (rudimentary, ~95% service level).
  • Reorder point = safety stock + (avg daily orders × avg lead time).
  • Safety stock is a buffer against demand variability and lead time variability; reorder point triggers timely replenishment without dipping into the buffer.
  • This is a simplified model; real‑world systems often use joint distributions and dynamic safety stock.

Inventory Management with Spreadsheet Functions

Inventory management answers two practical questions: when to order and how much to order. Holding too much stock ties up capital and incurs storage costs; holding too little risks stockouts. Spreadsheets provide tools to automate these decisions.

Economic Order Quantity (EOQ) – Concept

EOQ is a classic formula that balances ordering cost (delivery charges per order) and holding cost (storage, capital lockup). The optimal order quantity minimises total cost:

EOQ=2DSH\text{EOQ} = \sqrt{\frac{2DS}{H}}

where DD = annual demand, SS = cost per order, HH = holding cost per unit per year.
The lecture mentions EOQ only as background; in practice, a simpler rule based on reorder point and on-hand inventory is used.

Reorder Point & Safety Stock

  • Reorder point – the inventory level that triggers a new order. It accounts for lead time and expected demand.
  • Safety stock – extra buffer to cover demand fluctuations.
  • The lecture assumes reorder point is given per product (e.g., 50 for Mosambi, 28 for Tomato Hybrid, 69 for another product).

Calculating On-Hand Inventory

On-hand inventory at any moment is the difference between total purchases and total sales (orders):

On Hand=PurchasesSales\text{On Hand} = \sum \text{Purchases} - \sum \text{Sales}

Using SUMIF, you sum quantities by matching a product ID.

Product IDProduct NamePurchases (SUMIF from Purchase Master)Sales (SUMIF from Order Master)On Hand
P001Tomato Hybrid100072928

Negative on-hand indicates sold more than purchased – a data error (theft, recording mistake, or missing purchase). This must be corrected.

Extracting Product IDs from Combined Strings

If product data is stored as a combined string (e.g., "Orange P001"), extract the ID for lookup:

  • LEFT – when ID has fixed length (e.g., 5 characters): =LEFT(A2,5)
  • MID + FIND – when ID position varies:
    • Find the space: =FIND(" ", A2)
    • Extract from that position+1: =MID(A2, FIND(" ", A2)+1, LEN(A2)-FIND(" ", A2))

Exam tip: Use LEFT when product codes are fixed-length; use MID+FIND when they are variable-length. Always test edge cases (missing strings).

Decision: How Much to Order

If on-hand inventory is below the reorder point, order enough to bring it up to the reorder point; otherwise order zero.

\begin{cases} \text{Recorder Point} - \text{On Hand} & \text{if On Hand} \leq \text{Reorder Point} \\ 0 & \text{otherwise} \end{cases} $$ ```mermaid flowchart TD A[On-Hand <= Reorder Point?] -->|Yes| B[Order = Reorder Point - On-Hand] A -->|No| C[Order = 0] ``` **Example from lecture**: - Mosambi: On-hand = 41, Reorder Point = 50 → Order 9 - Tomato Hybrid: On-hand = 9, Reorder Point = 28 → Order 19 - Another product: On-hand = 29, Reorder Point = 69 → Order 40 ### Additional Use: Theft Detection If the spreadsheet-calculated on-hand differs from a physical count (and no recent purchases/sales explain it), it may indicate theft or loss. Regular reconciliation becomes a control mechanism. **Key takeaways** - Inventory management requires knowing **when** (reorder point) and **how much** (order quantity). - **On-hand inventory** = total purchases minus total sales, computed using **SUMIF**. - **Negative on-hand** is a red flag – must be resolved. - Order quantity rule: if below reorder point, order the difference; otherwise, zero. - Spreadsheet functions like **LEFT**, **MID**, and **FIND** extract product IDs for lookups. ### Recap: Core Concepts in Spreadsheets The module covered two broad workflows: **data ingestion and cleaning** from forms, and **inventory management** using derived metrics to produce actionable reorder decisions. All tools (text formulas, pivot tables, lookup functions, conditional logic) work together to turn raw entries into a dynamic inventory system. ### Data from Forms and Text Cleaning - Forms feed raw data (purchases, sales) directly into a sheet — multiple teams can submit to the same master table. - **Text formulas** clean or extract substrings: **LEFT**, **MID**, **FIND**, **LEN** (length) are the core set. Use them to parse structured entries (e.g., extract order IDs, dates). ### Inventory Metrics – The Decision Chain The inventory logic builds layer by layer: ```mermaid flowchart LR A[Form data] --> B[Pivot tables: avg daily consumption & std dev] B --> C[Safety stock = Max(2× std dev) × Max lead time] C --> D[Reorder point = Avg consumption × Avg lead time + Safety stock] D --> E[Order quantity = Reorder point – On-hand inventory] ``` | Metric | Definition | Purpose | |---|---|---| | **Lead time** | Days between placing and receiving an order | Measure delay | | **Average lead time** | Mean of recorded lead times | Baseline for reorder timing | | **Max lead time** | Highest observed lead time | Worst‑case scenario | | **Average daily consumption** | Mean units sold per day (from pivot table) | Demand rate | | **Standard deviation of daily consumption** | Variation in demand | Quantifies uncertainty | | **Safety stock** | Extra stock held to cover uncertainty | Prevents stockouts during delays / demand spikes | | **Reorder point** | Inventory level that triggers a new order | When to order | | **On‑hand inventory** | Current stock (from purchases − sales) | Starting point for order size | #### How the numbers work (illustrative, no real numbers given) - From a pivot table, obtain **average daily consumption** $\mu_c$ and its **standard deviation** $\sigma_c$. - Set **safety stock** as: $$\text{Safety Stock} = 2 \cdot \sigma_c \cdot \text{Max Lead Time}$$ (The “max” taken as $2\times$ standard deviation.) - Compute **reorder point**: $$\text{Reorder Point} = \mu_c \cdot \text{Avg Lead Time} + \text{Safety Stock}$$ - **How much to order**: $$\text{Order Quantity} = \text{Reorder Point} - \text{On-Hand Inventory}$$ > **Exam tip:** The two‑pivot‑table approach is the key skill: one for average consumption, another (successive) for variation. Always double‑check that the second pivot table uses the same source data with appropriate aggregation (STDEV). ### Key Functions & References - **SUMIF** – conditional sum (e.g., total sales for a product). - **VLOOKUP** – fetch data from another table by key (e.g., product name → unit cost). - **IF** – logical branching in formulas. - **Absolute vs. relative reference** – use `$` to lock rows/columns when copying formulas across a range (e.g., `$A$1` for a fixed lookup value). ### Pivot Tables – Two Successive Uses 1. **First pivot:** group sales data by day → get **average daily consumption**. 2. **Second pivot:** group the same data by day → get **standard deviation** of daily consumption (using the STDEV aggregation). This demonstrates how the same raw data can yield both central tendency and dispersion with a small shift in pivot configuration. ### Practical Extensions (mentioned, not covered) - Send automatic email nudges when order quantity > 1. - Integrate external APIs for price updates or delivery tracking. - Handle **multiple line items** per order, **perishability** (inventory age), **FIFO/LIFO** lot tracking, and **Economic Order Quantity (EOQ)** . **Key Takeaways** - **Forms + text formulas** let you collect and clean data automatically. - **Inventory decisions** rely on lead time, consumption (mean & std dev), safety stock, and reorder point. - **Two successive pivot tables** extract both average and variation from the same dataset. - **SUMIF, VLOOKUP, IF** and **absolute references** are the building blocks for dynamic spreadsheets. - The system outputs a concrete **order quantity** — not just tracking, but **actionable insight**. ### Automation in Google and Excel - I **Automation** transforms a static spreadsheet into an intelligent system that acts, reacts, and communicates automatically. The most accessible entry point is **macros** — essentially a robot that records your manual actions (formatting, data cleanup, copy-paste) and replays them with a single click. No coding required to begin. ### What is a Macro? A macro is a stored sequence of operations. You **record** a macro once, then trigger it to repeat the exact same steps on new data. This is ideal for repetitive tasks like: - Adding bold headings and cell colors - Setting borders - Cleaning or restructuring data > **Behind the scenes:** Every macro is generated as code. In Microsoft Excel the code is written in **VBA** (Visual Basic for Applications). In Google Sheets macros produce **Google Apps Script** (JavaScript-based). The recording tool writes the code for you. ### Recording a Macro – Demonstration 1. **Select** a range (e.g., a row) that you want to format. 2. In Google Sheets: **Extensions → Macros → Record macro**. 3. Choose **Relative reference** (explained below). 4. Perform the formatting actions (e.g., bold, italic, green text, gray background). 5. Click **Save** – name the macro (e.g., `Color Row`) and assign an optional shortcut key (e.g., `Ctrl+Shift+Alt+1`). 6. To reuse: select another row, then run the macro via **Extensions → Macros → [macro name]** or use the keyboard shortcut. ### Relative vs. Absolute References in Macros The choice during recording determines whether the macro always acts on the same cells or adapts to the current selection. | Reference type | Behavior | Use case | |---|---|---| | **Absolute** | Macro always applies to the exact cells you recorded (e.g., always row 3). | Formatting a fixed header row. | | **Relative** | Macro applies relative to the cell you select when running it. If you recorded formatting on row 3 and later select row 5, the macro applies the same formatting to row 5. | Formatting any arbitrary row – the macro “follows” your selection. | > **Exam tip:** For reusable macros that work anywhere in the sheet, **always use relative references** during recording. Absolute references lock the action to one location, making the macro nearly useless for repetitive tasks. ### The Code Behind the Magic When you record a macro, the tool automatically writes the corresponding script. In Excel it becomes VBA; in Google Sheets it becomes an Apps Script function. You can view and edit the code later – opening the door to more advanced automation without starting from scratch. **Key takeaways** - Macros automate repetitive formatting, data cleanup, and similar tasks without coding. - Record a macro by performing the steps once; replay it anytime. - **Relative references** let the macro work on whatever cell/row you select. - **Absolute references** fix the macro to the original recorded location. - Behind every macro is runnable code (VBA for Excel, Apps Script for Google Sheets) that can be edited for finer control. ### What is Google App Scripts? **Google App Scripts** is a JavaScript‑based scripting platform that extends Google Workspace products, especially **Google Sheets**. It allows you to write **custom functions**, automate processes, connect sheets with external APIs, react to events, send emails, and generate documents. Access it via **Extensions → App Scripts** inside a Sheet. ### Creating Custom Functions App Scripts lets you write your own formulas that behave exactly like built‑in ones. **Example – a `customCubic` function:** ```javascript function customCubic(number) { return number * number * number; } ``` - Save the script, then deploy (or skip deployment for personal use). - In any cell, type `=customCubic(3)` → returns `27`. - Any JavaScript logic is usable; custom functions can reference cell ranges and perform complex calculations. > **Exam tip:** Custom functions must be pure JavaScript. They appear in the autocomplete as you type the function name. If you share the sheet, the script must be deployed properly. ### Working with Sheets: Classes and Methods App Scripts uses **classes** (e.g., `SpreadsheetApp`, `Sheet`, `Range`) and **methods** to interact with spreadsheets. The official developer documentation is the definitive guide. **Example from the docs – reading product names:** ```javascript function logProductNames() { var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getDataRange(); var data = range.getValues(); for (var i = 0; i < data.length; i++) { Logger.log('Product name: ' + data[i][0] + ', Number: ' + data[i][1]); } } ``` - `SpreadsheetApp.getActiveSheet()` – gets the current sheet. - `getDataRange()` – captures all data in the sheet. - `getValues()` – returns a 2D array of cell values. - Iterate over rows and access columns by index (`data[i][0]`, `data[i][1]`). Besides reading/writing cells, App Scripts can send emails, interact with other Google services, and connect to external APIs – all through documented classes and methods. ### Triggers – Running Scripts Automatically Logic written in App Scripts can be set to run **automatically** using **triggers**. Triggers fire based on events (e.g., on edit, on form submit) or on a time‑driven schedule (e.g., every hour). This enables fully automated workflows without manual execution. ### Key Resources - **App Scripts guides** – comprehensive walkthroughs. - **Sheets–specific documentation** – covers classes, methods, and examples. - For those with coding experience, the official docs are the primary reference. **Key takeaways** - **Google App Scripts** is a JavaScript platform for extending Google Sheets. - **Custom functions** are written in JavaScript and behave like built‑in formulas. - Scripts interact with Sheets via classes (**SpreadsheetApp**, **Sheet**, **Range**) and methods. - **Triggers** enable scripts to run automatically on events or time‑based schedules. - Official developer documentation is the essential resource for learning and implementation. ### What Triggers Are **Triggers** automate the execution of Apps Script functions based on specific events or schedules. Instead of manually running a macro, a trigger lets the system call the function automatically. - **Time-driven triggers** – run code at a fixed schedule (e.g., every evening at 5 PM). - **Event-driven triggers** – run code when an action occurs (e.g., form submitted, cell edited, sheet opened). ### Types of Simple Triggers in Google Sheets | Trigger Event | Common Use | |---|---| | `onOpen()` | Create custom menus or UI | | `onEdit()` | Track changes, add timestamps | | `onFormSubmit()` | Send confirmation emails after form submission | | `onInstall()` | Run setup code when add-on is installed | > **Exam tip:** `onEdit()` captures the edited range via an `e` parameter—use `e.range` to apply logic only to certain columns. ### Worked Example: Daily Inventory Email Alert **Goal:** Automatically email the inventory manager every evening if any product’s “how much to order” (column index 11) is greater than 0. **Step-by-step script logic:** 1. Get the **Product Master** sheet (by name). 2. Fetch all data as a 2D array using `getRange().getValues()`. 3. Loop through rows. For each row: - Read product name (column index 1) and “how much to order” (column index 11). - If quantity > 0, append a line to a message string. 4. If message is not empty, send email using `MailApp.sendEmail(to, subject, body)`. ```javascript function inventoryMail() { var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Product Master'); var data = sheet.getDataRange().getValues(); var message = ''; for (var i = 0; i < data.length; i++) { var product = data[i][1]; var qty = data[i][11]; if (qty > 0) { message += product + ' needs to be ordered. Quantity needed: ' + qty + '\n'; } } Logger.log(message); // debug in Apps Script console if (message !== '') { MailApp.sendEmail('iimbspreadsheets@gmail.com', 'Inventory to Order', message); } } ``` **Deploying the trigger:** 1. In Apps Script editor, deploy as a **web app** (not add-on). 2. Authorize the script to access Gmail and Sheets. 3. Set up trigger via **Edit → Current project’s triggers**: - **Function:** `inventoryMail` - **Event source:** Time-driven - **Type:** Day timer, e.g., 5 PM–6 PM - Save and re-deploy. Result: The script runs automatically every day, checks the sheet, and emails the manager. ### Why Triggers Matter - Turn a one‑time macro into recurring automation (“set and forget”). - Reduce manual checking – the system alerts you only when action is needed. - Combine with other Google services: **MailApp**, **CalendarApp**, **DocsApp**, **URL Fetch** (to call external APIs). ### Beyond This Example - Pull data from an API and write to Sheets. - Generate automated reports and email as PDF. - Validate data entries on edit. - Merge Sheets with Google Docs to create personalized documents. - Build internal tools that behave like standalone applications. For Excel users: equivalent functionality exists via **VBA**, **Power Automate**, and **Office Scripts**. **Key takeaways** - **Triggers** = run code automatically on a schedule (time‑driven) or on user actions (event‑driven). - `MailApp.sendEmail()` lets you send notifications directly from Sheets. - Deploy as a web app and authorise once; triggers run under your account. - A trigger combined with a logic loop (e.g., inventory check) creates a real‑time alert system. - Apps Script is extensible to APIs, document generation, and custom tools. ### What is URL Fetch? **URL Fetch** is a built‑in Apps Script class (`UrlFetchApp`) that allows a spreadsheet to make HTTP requests to external APIs. Think of it as a **bridge** between your sheet and the rest of the internet — if a service exposes an API, your spreadsheet can talk to it. ```javascript let response = UrlFetchApp.fetch(url, options); ``` This works exactly like `fetch()` in JavaScript. It enables a spreadsheet to not only store data but also to **intelligently interact** with real‑time services and machine‑learning models. --- ### Common use cases for URL Fetch | Use Case | API Example | Benefit | |-------------------------|---------------------------------|---------------------------------------------| | Real‑time currency rates| exchangerate.host | Populate dashboards with live rates | | Stock prices / news | Financial data APIs | Auto‑update portfolio sheets | | CRM / ERP integration | Salesforce, Tally | Pull customer records, update order status | | Messaging | Twilio (WhatsApp, SMS) | Trigger alerts from sheet events | | AI content generation | Grok, OpenAI, Gemini | Auto‑generate replies, summaries, emails | > **Exam tip:** URL Fetch is what turns a passive spreadsheet into an active system that can read, write, and *think* by leveraging external APIs. --- ### Worked example: AI‑powered email replies from Google Forms **Scenario:** A photography business collects customer queries via Google Forms. We want every form submission to: 1. Trigger an Apps Script function. 2. Send the query to a free LLM (Grok) via URL Fetch. 3. Use the LLM’s reply to send a personalised, professional email back to the customer. 4. Log the response in the spreadsheet. #### Step‑by‑step process ```mermaid flowchart TD A[Customer submits form] --> B[Apps Script trigger: onFormSubmit] B --> C[Read last row: email & query] C --> D[Build payload for Grok API with prompt] D --> E[UrlFetchApp.fetch to Grok completions endpoint] E --> F[Parse API response -> get generated email text] F --> G[Send email via MailApp] G --> H[Write AI response back to sheet] ``` #### Key code concepts (not full code, but the logic) - **Trigger:** `onFormSubmit(e)` — automatically runs when the linked form receives a response. - **Reading data:** The event object `e` gives access to the active sheet; the last row contains the new submission (email in column B, query in column C). - **Building the request:** Construct a JSON payload with: - `model`: e.g., `llama3` (free via Grok cloud). - `messages`: a system message (you are a professional email generator) and the user query. - `authorization`: Bearer token (your API key from Grok cloud). - **Calling the API:** `UrlFetchApp.fetch(url, options)` sends a POST request to Grok’s completions endpoint. - **Parsing the response:** Extract the text content from the nested JSON response. - **Sending email:** `MailApp.sendEmail(email, subject, body)` with the AI‑generated text. - **Logging:** Write the response back into the sheet for audit. #### What the user sees | Column (Form Responses) | Data | |------------------------|------| | Timestamp | 2025-03-25 10:00 | | Email (B) | customer@example.com | | Query (C) | “I want photos of my dog Scooby – 3rd birthday” | | AI Reply (D, added by script) | “Dear Client, thank you for reaching out. We’d be thrilled to photograph Scooby’s birthday...” | The customer receives a warm, personalised email moments after submitting the form. > **Exam tip:** Free LLM APIs (Grok, some Gemini tiers) give a limited number of requests per day — always check the quota before deploying in production. For real‑world use, consider paid tiers or rate‑limiting. --- ### Key takeaways - **URL Fetch (`UrlFetchApp`)** connects Google Sheets to any external API — a bridge to real‑time data and AI. - Useful for: live currency, stock prices, CRM sync, messaging, and **LLM‑powered automation**. - The worked example combines **onFormSubmit trigger**, **URL Fetch to Grok**, and **MailApp** to auto‑generate and send personalised email replies. - The system can log the AI response back into the sheet for record‑keeping. - This demonstrates moving beyond logic‑based automation (IF formulas) to **intelligent content generation** using large language models. - Always **authorise** the script once (prompted on first run) and set up the trigger via the Apps Script editor (`Edit → Current project’s triggers`).
Study this interactively — ask questions and quiz yourself — in the study app, or see how it connects across the degree in the concept map.