PeaBox Lab › PeaLang › Learn › Chapter 16 › Lesson 4

Part III — Advanced Systems · Chapter 16 · Lesson 4 of 6 · 12 min read

Lesson 4: Joins, Grouped Aggregations, Nulls, Pivots, Unpivots, and Windows

Lesson level: Advanced

Purpose: Combine and summarize tables without losing track of keys, grain, missing values, or ordering.

Learning objectives. Explain join types and cardinality; define grouped metrics; specify null policy; reshape long and wide data; distinguish aggregation from windows; and test relational operations using small adversarial fixtures.

Implementation convention. Operation names describe relational concepts. Supported signatures, join options, expression forms, and window behavior must be verified against the installed PeaLang data implementation. These pages do not establish new runtime guarantees.

Learning objectives

By the end of this lesson, you will be able to:

4.1 Joins connect records through keys

A join associates rows using an explicit matching condition. Joining orders to customers by customer_id adds customer attributes to order records. Joining by a customer’s display name instead can confuse different people or organizations with similar names.

An inner join retains matching combinations. A left join also preserves unmatched left records, with missing right-side attributes. A full outer join can expose unmatched records from either side. Choose the behavior according to the question, not as a default habit.

Illustrative example. Orders refer to customers C-A and C-B. The reference table contains C-A but not C-B. An inner join omits the C-B order. A left join preserves it and exposes the missing customer match. If completeness matters, the latter makes the defect easier to reconcile.

Write a join contract: left grain, right grain, key fields, required key types, expected relationship, unmatched-record policy, duplicate-key policy, and output names. Resolve field-name collisions deliberately rather than relying on unspecified suffix conventions.

Guided practice. Choose a join for enriching every valid order, finding orders without a customer reference, and comparing two complete source inventories. Explain which unmatched records must remain visible.

Common mistake: a successful join is not proof of correct relationships. Wrong keys can produce plausible matches; incomplete references can silently remove rows.

Review prompt: Why should a missing customer match be distinguished from a customer record whose optional region is null?

4.2 Cardinality: predict multiplication before joining

Join cardinality describes how many matches a key can produce. One-to-one means at most one record on each side for a key. Many-to-one allows repeated left keys but requires a unique right key. One-to-many and many-to-many can expand the output.

Order enrichment usually expects many orders to one customer reference. If the customer table contains duplicate customer_id values, one order can acquire multiple matches. The table may still look reasonable while additive measures are repeated.

Illustrative diagnostic. A customer reference contains both an old and a current record for C-A. Joining every order to both versions duplicates enrichment. Resolve the reference under an approved current-record rule, or use a time-aware relationship with explicit validity conditions. Arbitrary distinct does not establish which version is correct.

Inspect cardinality before the join. Check required keys for missing values and duplicates. Declare which side must be unique. After the join, reconcile left business keys, unmatched references, and unexpected repetition. If the runtime lacks a cardinality-validation option, implement a separate verified check.

Composite keys can be necessary. An order_id unique within a source system is not necessarily unique across all sources. A source_system and order_id combination can express the actual identity. Both sides must use the same composite contract.

Null-key matching is implementation-dependent. Do not assume a null customer identifier matches another null identifier. Decide whether null keys are invalid, unmatched, or permitted under a special rule, then test the actual engine.

Guided practice. Sketch left and right fixtures containing a unique reference, a missing reference, a duplicate reference, and a null key. Predict whether each left order is retained, expanded, or rejected under your policy.

Common mistakes. Checking only total row count can miss offsetting errors. A dropped order and a duplicated order can conceal one another. Reconcile key identities and match multiplicities, not just the headline total.

Applied question: How would you detect that a supposed many-to-one join has become many-to-many after a supplier changes its export?

Invariant: When enrichment promises one result per valid order, each retained order key must occur exactly once in the enriched output.

4.3 Grouped aggregation: define every measure

Grouping partitions records by key values. Aggregation summarizes each partition, producing a new grain. Grouping orders by region and reporting total order value produces one row per region, not one row per order.

Define each measure independently: name, population, source field, aggregation, units, null treatment, and output representation. Order count may count rows only after deduplication ensures one row per order. Customer count may require distinct customer keys rather than the number of order rows.

Illustrative specification. From validated approved orders, group by region and currency. Report order_count, known_amount_count, and total_known_amount. Keeping currency in the grouping prevents unlike monetary values from being added without a conversion contract.

Count and non-null count answer different questions. A group can contain order records while some measures are missing. Report completeness alongside a total when missing amounts are allowed; otherwise a partial total can appear complete.

Filters before and after aggregation have different meanings. Filtering order amount before grouping selects individual orders. Filtering total_known_amount after grouping selects regional summaries. The two conditions are not interchangeable even when they use a similar threshold.

Do not average group averages blindly. To recombine means, retain the corresponding counts and sums under the same missing-value policy. A region with few observations should not automatically receive the same weight as a region with many observations.

Empty input needs an explicit output contract. Decide whether the summary is empty or contains designated groups with no observations. A total over no observations and a total measured to be zero are conceptually different; the representation must reflect the intended meaning.

Guided practice. Define order_count, customer_count, total_known_amount, and average_known_amount. State which source keys and denominators each needs. Explain which measures are additive across disjoint groups.

Common mistakes. Joining to an expanded child table before summing repeats parent amounts. Mixing currencies invalidates totals. Dropping nulls without a completeness indicator overstates certainty. Averaging rounded summaries compounds error.

Review prompt: How does changing the group key from region to region plus currency change the output grain and the interpretation of the totals?

4.4 Null-aware relational reasoning

Null can originate in source data, normalization, or an unmatched join. These origins matter. An optional customer note being absent is not the same event as an entire customer reference being missing. Preserve enough lineage to explain why a field is unknown.

A table engine’s null behavior must be established for comparisons, filters, joins, grouping, arithmetic, and aggregation. Do not import scalar-language assumptions or another library’s conventions. Use small executable fixtures to document the actual behavior before relying on it.

Proposed contract. Required order identifiers and amounts are rejected when missing. Optional customer regions remain unknown. Unmatched customer references receive a separate match-status field. Regional reporting includes a clearly labeled unknown-region category or a separate unmatched report according to the reporting brief.

Filling a null is a business transformation. Replacing a missing amount with zero says that no value was recorded, not merely that the value is unknown. Replacing missing region with a label can be acceptable for reporting if the label remains distinguishable from a real region.

Dropping null records changes population. Before doing so, state which fields trigger removal and whether the discarded records are valid but incomplete or actually malformed. Record the effect separately from an ordinary status filter.

Annotated example. After a left join, customer_region is null. Check match status first. If the customer did not match, investigate the reference boundary. If the customer matched but its region is absent, follow the optional-field policy. A single null value does not identify the cause.

All-null groups need special attention. A known total over observed values should not be presented as a complete group total when no values are available. Provide an observation count or completeness state alongside the measure.

Guided practice. Create fixtures for a source null, a failed conversion, an unmatched join, an optional absent attribute, and an all-null measure group. Specify the expected outcome for each operation.

Common mistake: blanket fill operations can erase evidence of broken relationships. Apply fills only to named fields under explicit rules and retain provenance where required.

Review prompt: What evidence distinguishes a genuine zero result from an unknown result displayed as zero?

4.5 Pivot and unpivot: reshape with an explicit cell rule

A long table stores categories as values. A wide table stores selected categories as separate columns. Pivot converts from long to wide; unpivot moves selected wide columns into category-and-value records. The best shape depends on the consumer and the next operation.

A monthly regional summary can be long, with region, month, currency, and total_value fields. A presentation may prefer one month per column. Keeping a canonical long form usually makes filtering, grouping, and later category additions easier to manage.

A pivot specification needs row keys, a category field, a value field, and a rule for repeated cells. If more than one source record maps to the same row-key and category combination, the operation must aggregate deliberately or reject ambiguity.

Illustrative recipe: begin with one summary per region, currency, and month; pivot month into approved report columns; place total_value in each cell; reject duplicate region–currency–month summaries. Do not let a default aggregation conceal an unexpected duplicate.

Missing cells require a contract. No observation for a region and month is not automatically a measured zero. A presentation may show a blank or a labeled missing state. If zero fill is justified, keep that decision explicit and distinguish it from incomplete source ingestion.

Unpivot requires an identifier set and a measure-column set. Unpivoting unrelated fields together can mix incompatible units. Amount columns and order-count columns should not become one undifferentiated value field without a measure-kind and representation policy.

A pivot followed by unpivot is not necessarily reversible. Aggregation loses detail. Filling missing cells changes semantics. Category labels can collide with existing field names. Test reversibility only for the specific contract, not as a universal property.

Guided practice. Describe the canonical long summary and its wide presentation version. State row keys, allowed month categories, duplicate-cell policy, and missing-cell representation. Explain which information is intentionally lost.

Common mistake: dynamically creating a column for every observed category can produce an unstable interface and excessive width. Bound or validate categories when consumers require a fixed schema.

Review prompt: Why should a pivot be treated as a reporting transformation rather than proof that the underlying observations are complete?

4.6 Windows: context without collapsing rows

A grouped aggregate reduces a partition to summary rows. A window calculation can attach contextual results to existing rows. This distinction lets each order remain visible while receiving a regional total, a within-customer position, or a running measure.

A window definition usually needs a partition, an ordering rule where relevant, and a frame describing which neighboring records contribute. The exact capabilities and syntax are implementation-specific; verify them before treating a conceptual window as executable PeaLang.

Illustrative example. For each customer, order records by ordered_at and a stable order key. Attach a running total over the current and preceding records. Customer partitions must remain separate; one customer’s values must not enter another’s running result.

Ordering ties require deliberate treatment. Equal timestamps do not establish a unique order. Add a stable key when sequence matters. Also distinguish a row-based frame from a time-based frame: a fixed number of preceding records can span very different durations.

Window boundaries matter. A trailing window excludes future observations. A centered window may include them, making it unsuitable for a feature intended to be known at prediction time. State whether the current row contributes and what happens when the history is shorter than the requested frame.

Lag and lead describe relative positions within an ordered partition. Their missing first or last values should remain explicit. Do not replace a missing previous value with zero merely to make a difference calculation run.

Attaching a partition total repeats that total on every detail row. It is useful for comparison but usually not additive across those rows. Summing the attached total again creates double counting. Name contextual fields so readers do not mistake them for row-level amounts.

Guided practice. Define a customer running total and a regional contextual total. State partition keys, ordering, frame, null behavior, and output grain. Identify which result can be summed safely and under what conditions.

Common mistakes. Omitted partitioning mixes entities. Nondeterministic ties create unstable lag values. Centered windows leak future information. Repeated partition totals are mistaken for additive measures.

Review prompt: How does attaching a regional total to every order differ from producing one summary row per region?

4.7 Hands-on lab: Relational correctness workbench

Scenario. Use synthetic order, customer-reference, and order-tag tables to demonstrate the operations in this lesson. Keep their grains separate. Implement only verified runtime operations; document any adapter needed to satisfy a conceptual requirement.

Fixture design. Include a valid customer match, an unmatched customer, duplicate customer references, multiple orders for one customer, an order with no tags, missing optional region, two currencies, and tied order timestamps. These cases test relationships rather than only ordinary arithmetic.

Join task. Enrich orders while preserving one result per valid order. Check reference uniqueness first. Reject conflicting reference duplicates or apply a documented version-selection policy. Produce an unmatched-key report and show that no order vanished unnoticed.

Aggregation task. Produce region-and-currency summaries with distinct measure definitions and completeness indicators. Explain why order counts, customer counts, and known-amount counts can differ. Do not sum amounts across currencies without a conversion contract.

Reshape task. Pivot the canonical summary into an approved presentation shape. Declare category order, duplicate-cell handling, and missing-cell meaning. Unpivot the result and compare only the properties your contract promises to preserve.

Window task. Attach a customer running measure with deterministic ordering. Verify that the first row, tied timestamps, missing values, and partition boundaries behave as specified. Ensure no future record contributes to a trailing measure.

Review questions. Which join preserves unmatched left records? How can duplicate reference keys inflate a total? What distinguishes count from non-null count? Why can pivot lose detail? What determines a window frame? Which attached totals are non-additive?

Applied challenge. Explain how a single incorrect join can affect both the grouped summary and the window output. Propose independent key reconciliation and measure reconciliation checks that detect the defect before publication.

Acceptance criteria. Every operation has a grain statement, key rule, null rule, and observed test evidence. Expected and observed outcomes are recorded separately. Any unsupported option remains a documented gap rather than a fabricated API.

Lesson summary. Relational correctness depends on relationships, not just successful execution. Protect cardinality, population, units, missing-value meaning, and ordering at each transformation.

Common mistakes

Review questions

Applied challenge

Join orders, customers, and products; report unmatched records separately; compute revenue by region and month; pivot months into columns for a report; and add each customer's rank by revenue within their region. Prove that the total revenue is the same before and after every reshaping step.

Lesson summary

Joins, aggregations, pivots, and windows are powerful but can silently change row counts or meaning. Check key uniqueness, count unmatched rows, handle nulls explicitly, aggregate from base data, and reconcile totals after each step.

Lesson status: Ready for review.

← Previous Next →