DB Olympics

Queries · q394 · Director of Fulfilment Operations · week 2, night 2

Which specific products drive discrepancies at the three standout apparel sites

“At Atlanta (Cragsley Outfitters), Reading (Marrowby & Vane) and Den Haag (Studio Vrij) — the three sites with by far the most stock-count discrepancies — is the problem spread across the catalog, or concentrated in a handful of specific products/size-color variants?”

Manager · asked the questionTomasz NowakDirector of Fulfilment Operations. Ran warehouses for a large retailer before joining.
Analyst · planned the reportFatima ZahraDefinition-minded: checks what each field really records before relying on it.
Engineer · wrote the SQLGraceWrites tidy, layered CTEs with descriptive names, one step per CTE, then a final select.

Fictional people at a fictional company, each played by a language-model agent. Who they are and what they are told

  1. A business event lands on the Director of Fulfilment Operations's desk

    Week 1; shared with Tobias Lindqvist, Chief Financial Officer

    Auditors and merchants question inventory accuracy. How often do counts, adjustments and reservations disagree with recorded stock, where, and why?

  2. Tomasz Nowak writes to Fatima Zahra

    The manager, at the start of week 2

    Subject: Re: Inventory accuracy memo — good start, a few things need tightening before I take this to Tobias/auditors

    Fatima,

    This is a strong first cut — the two-mechanism split and the "reservations are fine" finding are exactly what I needed, and I can rule out overselling as a risk now. A few things surprised me and I want them firmed up before we put numbers in front of auditors:

    1. The 24% rise in monthly shrinkage worries me more than the headline total. Is that a steady climb all year, or did it step up around a specific point (new site opening, staffing change, holiday peak)? I want to know if we're looking at a slow-burn trend or something that started at a moment we can point to.
    2. The loss-reason split being almost perfectly even across three categories makes me suspicious, not reassured. Before we size any provision off that split, I want to know whether that's a genuine pattern or an artifact of how staff pick a reason from a dropdown (e.g., defaulting or cycling through options). Can you sanity-check whether specific people, shifts, or sites are behind the "theft-suspected" tag specifically — that's the one that would actually worry legal and the auditors.
    3. On the December 31st batch — I need to understand the "why," not just the "who." If this is confirmed as a real annual B2B stocktake, fine. But I want to understand why a positive correction of that size existed in the first place — were those units sitting miscounted all year, or is this a sign that we simply don't track B2B/bulk inventory day-to-day the way we do pick locations? That has different implications for the auditors than just "we run quarterly/annual stocktakes."
    4. On the apparel/footwear concentration, I want specifics, not just category names. Is this spread evenly across our apparel merchants and sites, or does it cluster around particular sites, shifts, or size runs? If it's a handful of locations, that's a training/process fix I can act on this quarter; if it's spread everywhere, that's a bigger systemic question about how we handle high-variant SKUs generally.

    If you can only run two this week, make it #1 and #2 — those directly affect what Tobias and I say about trend direction and provisioning, which is what the auditors will press hardest on.

    Thanks — good work.

    Tomasz

  3. Fatima Zahra plans the night

    The analyst · week 2, night 2, request 3 of 3

    Night 1 settled #1 and #2 confidently, so I'm moving to #3 and #4 tonight.

    #1 resolved: events_per_active_location hovers in a tight 4.6-5.9 band all year with no upward drift (Jan ~5.2-5.4, Dec ~5.2-5.3) — essentially flat. The raw event count rise tracks almost exactly with new warehouses coming online (23 new warehouses opened across the year, cumulative matches the ~85→111 growth in active locations). So the "24% rise" is a scale effect from warehouse rollout, not a genuine per-location worsening, and there's no identifiable step-change moment — I'm confident in this and will write it up without more slots.

    #2 resolved, and more decisively than expected: pct_theft_of_own_adjustments sits in a tight band (~15-23%) across essentially every one of the 35 staff identities and every warehouse, and — tellingly — each named staff member's total_adjustments_logged exactly equals one specific warehouse's total (Christopher Evans = 1,506 = Atlanta's total; Omar Taylor = 1,058 = Reading's total, etc.). That's a 1:1 staff-to-warehouse mapping, not real distributed rosters, and distinct_staff_logging_theft_here is never more than 1 per site. Combined with avg_hour_of_day clustering at ~11-12 (UTC) for nearly everyone regardless of which country their warehouse is in, this looks like a systematic/automated tagging pattern, not incident-by-incident human investigation. I'm flagging this as a data-provenance caveat for the memo rather than spending more slots on it.

    Tonight: one report for #3 (does the B2B/bulk segment get routine counts at all, or only the Dec-31 catch-up — using the "pick-only" finding and the 8 B2B tenants identified from last week's correction report as the test group), and two reports for #4 (is the apparel concentration driven by genuine elevated rate per location or just by warehouse size, and which specific products/variants are actually driving it at the three standout sites: Atlanta/Cragsley, Reading/Marrowby & Vane, Den Haag/Studio Vrij — notably the same three merchants Support Ops flagged as generating 34% of all support tickets).

    Which specific products drive discrepancies at the three standout apparel sites
    Question
    At Atlanta (Cragsley Outfitters), Reading (Marrowby & Vane) and Den Haag (Studio Vrij) — the three sites with by far the most stock-count discrepancies — is the problem spread across the catalog, or concentrated in a handful of specific products/size-color variants?
    One row per
    product variant, restricted to stock_adjustments rows at these three specific warehouses in 2025: Atlanta Fulfilment Centre, Reading Fulfilment Centre, Den Haag Fulfilment Centre
    Columns
    • warehouse_name
    • product_name
    • sku
    • variant_name (product_variants.name, which typically encodes size/color)
    • adjustment_count (count of stock_adjustments rows for this variant at this warehouse)
    • pct_theft_reason (% of this variant's adjustments at this warehouse tagged 'Missing - suspected theft', rounded 1dp)
    • distinct_days_affected (count of distinct calendar dates with >=1 adjustment for this variant at this warehouse)
  4. Grace writes the SQL

    The engineer · 1 dry run on the empty schema, then the submission

    Dry run 1 · STATUS: COMPILES (dry run on the empty schema, no data read)
    WITH three_warehouses AS (
      SELECT id, name FROM warehouses
      WHERE name IN ('Atlanta Fulfilment Centre','Reading Fulfilment Centre','Den Haag Fulfilment Centre')
    ),
    adjustments AS (
      SELECT sa.variant_id, sa.reason, sa.created_at, w.name AS warehouse_name
      FROM stock_adjustments sa
      JOIN stock_locations sl ON sl.id = sa.stock_location_id
      JOIN three_warehouses w ON w.id = sl.warehouse_id
      WHERE sa.created_at >= DATE '2025-01-01' AND sa.created_at < DATE '2026-01-01'
    ),
    variant_info AS (
      SELECT pv.id AS variant_id, pv.sku, pv.name AS variant_name, p.name AS product_name
      FROM product_variants pv
      JOIN products p ON p.id = pv.product_id
    ),
    aggregated AS (
      SELECT
        a.warehouse_name,
        vi.product_name,
        vi.sku,
        vi.variant_name,
        COUNT(*) AS adjustment_count,
        ROUND(100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_theft_reason,
        COUNT(DISTINCT DATE(a.created_at)) AS distinct_days_affected
      FROM adjustments a
      JOIN variant_info vi ON vi.variant_id = a.variant_id
      GROUP BY a.warehouse_name, vi.product_name, vi.sku, vi.variant_name
    )
    SELECT
      warehouse_name,
      product_name,
      sku,
      variant_name,
      adjustment_count,
      pct_theft_reason,
      distinct_days_affected,
      COUNT(*) OVER () AS total_distinct_variants
    FROM aggregated
    ORDER BY adjustment_count DESC, warehouse_name ASC, sku ASC
    LIMIT 50

    “Looks good. Submitting.”

    Submitted · the SQL of the last dry run, unchanged · Submitted to tonight's batch. Your work on this request is done.

    “Submitted. Summary of what the query does: - Scope: stock_adjustments in 2025 (created_at in [2025-01-01, 2026-01-01)), restricted to the three named warehouses via stock_locations → warehouses. - Grain: one row per warehouse × product variant, joining product_variants → products for names/SKU. - Measures: adjustment_count (row count), pct_theft_reason (share tagged 'Missing - suspected theft', 1dp), distinct_days_affected (distinct calendar dates with ≥1 adjustment). - Ordering/cap: sorted by adjustment_count desc, then warehouse_name, then sku; capped at 50 rows via LIMIT 50. - Extra: added total_distinct_variants, a window-function count of all qualifying variant rows (computed before the cap), so the printed report also shows how many variants total had discrepancies even though only the top 50 are listed — flagged this addition in the submit note.”

  5. The report comes back overnight

    As Fatima Zahra saw it, from the small dataset the agents worked on

    warehouse_name             | product_name                          | sku                | variant_name    | adjustment_count | pct_theft_reason | distinct_days_affected | total_distinct_variants
    ---------------------------+---------------------------------------+--------------------+-----------------+------------------+------------------+------------------------+------------------------
    Atlanta Fulfilment Centre  | Chunky Lambswool Scarf                | CO-10927-FORE      | Forest Green    |                5 |             20.0 |                      5 |                    2927
    Den Haag Fulfilment Centre | Fine Knit Merino Scarf                | SV-10293-BLAC      | Black           |                5 |              0.0 |                      5 |                    2927
    Atlanta Fulfilment Centre  | Pom-Pom Merino Wool Beanie            | CO-10248-WHIT      | White           |                4 |              0.0 |                      4 |                    2927
    Atlanta Fulfilment Centre  | Checked Scarf                         | CO-10530-GREY      | Grey Marl       |                4 |             25.0 |                      4 |                    2927
    Atlanta Fulfilment Centre  | Fisherman Beanie                      | CO-10745-FORE      | Forest Green    |                4 |              0.0 |                      3 |                    2927
    Den Haag Fulfilment Centre | Ribbed Merino Wool Beanie             | SV-10004-CHAR      | Charcoal        |                4 |              0.0 |                      4 |                    2927
    Den Haag Fulfilment Centre | Oversized Lambswool Scarf             | SV-10291-WHIT      | White           |                4 |             50.0 |                      4 |                    2927
    Reading Fulfilment Centre  | Fisherman Recycled Wool Beanie        | MV-10038-GREY      | Grey Marl       |                4 |              0.0 |                      4 |                    2927
    Reading Fulfilment Centre  | Pom-Pom Merino Wool Beanie            | MV-10544-RUST      | Rust            |                4 |             50.0 |                      4 |                    2927
    Atlanta Fulfilment Centre  | Graphic Organic Cotton Kids T-Shirt   | CO-10089-1213-LILA | 12-13Y / Lilac  |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Ribbed Beanie                         | CO-10205-GREY      | Grey Marl       |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Striped Organic Cotton Kids T-Shirt   | CO-10221-45Y-NAVY  | 4-5Y / Navy     |                3 |             33.3 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Oversized Merino Scarf                | CO-10388-SKYB      | Sky Blue        |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Cardigan Cashmere Blend Sweater       | CO-10400-S-CAME    | S / Camel       |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Fisherman Recycled Wool Beanie        | CO-10487-WHIT      | White           |                3 |             33.3 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Ribbed Merino Wool Beanie             | CO-10609-GREY      | Grey Marl       |                3 |             33.3 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Bootcut Organic Denim Jeans           | CO-10682-W36-BURG  | W36 / Burgundy  |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Pullover Loopback Cotton Hoodie       | CO-10786-XS-CHAR   | XS / Charcoal   |                3 |              0.0 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Oversized Scarf                       | CO-11023-OLIV      | Olive           |                3 |             33.3 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Pullover Organic Cotton Fleece Hoodie | CO-11172-XL-ECRU   | XL / Ecru       |                3 |              0.0 |                      3 |                    2927
    Den Haag Fulfilment Centre | Checked Scarf                         | SV-10062-ECRU      | Ecru            |                3 |             33.3 |                      3 |                    2927
    Den Haag Fulfilment Centre | Checked Scarf                         | SV-10115-WHIT      | White           |                3 |             33.3 |                      3 |                    2927
    Den Haag Fulfilment Centre | Fisherman Beanie                      | SV-10221-BURG      | Burgundy        |                3 |              0.0 |                      3 |                    2927
    Den Haag Fulfilment Centre | Checked Merino Scarf                  | SV-10296-SAND      | Sand            |                3 |              0.0 |                      3 |                    2927
    Reading Fulfilment Centre  | Knitted Viscose Dress                 | MV-10060-XL-BLAC   | XL / Black      |                3 |              0.0 |                      3 |                    2927
    Reading Fulfilment Centre  | Fisherman Beanie                      | MV-10496-RUST      | Rust            |                3 |             33.3 |                      3 |                    2927
    Reading Fulfilment Centre  | Pom-Pom Beanie                        | MV-10533-BLAC      | Black           |                3 |              0.0 |                      3 |                    2927
    Reading Fulfilment Centre  | Fine Knit Lambswool Scarf             | MV-10618-FORE      | Forest Green    |                3 |              0.0 |                      3 |                    2927
    Reading Fulfilment Centre  | Ribbed Recycled Wool Beanie           | MV-10724-SAND      | Sand            |                3 |             33.3 |                      3 |                    2927
    Atlanta Fulfilment Centre  | Fine Knit Scarf                       | CO-10020-CAME      | Camel           |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Court Sneakers                        | CO-10026-38-SKYB   | 38 / Sky Blue   |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Oversized Lambswool Scarf             | CO-10034-BLAC      | Black           |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Chunky Lambswool Scarf                | CO-10062-WHIT      | White           |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Ribbed Recycled Wool Beanie           | CO-10067-WHIT      | White           |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Corduroy Shirt                        | CO-10068-S-BLAC    | S / Black       |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Bootcut Jeans                         | CO-10075-W36-GREY  | W36 / Grey Marl |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Overcoat Coat                         | CO-10079-XXL-BLAC  | XXL / Black     |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Crew Neck Cashmere Blend Sweater      | CO-10080-XL-SKYB   | XL / Sky Blue   |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Pom-Pom Merino Wool Beanie            | CO-10095-SKYB      | Sky Blue        |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Crew Neck Lambswool Sweater           | CO-10109-M-ECRU    | M / Ecru        |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | 3-Pack Organic Cotton Socks           | CO-10140-L-RUST    | L / Rust        |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Garment Dyed Loopback Cotton Hoodie   | CO-10143-L-OLIV    | L / Olive       |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Ribbed Merino Wool Beanie             | CO-10160-BURG      | Burgundy        |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Striped Cotton Jersey T-Shirt         | CO-10161-M-ECRU    | M / Ecru        |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Checked Merino Scarf                  | CO-10166-SAND      | Sand            |                2 |             50.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | V-Neck Merino Wool Sweater            | CO-10173-L-ECRU    | L / Ecru        |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Pom-Pom Beanie                        | CO-10178-FORE      | Forest Green    |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Pom-Pom Beanie                        | CO-10178-GREY      | Grey Marl       |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Court Recycled Canvas Sneakers        | CO-10186-37-NAVY   | 37 / Navy       |                2 |              0.0 |                      2 |                    2927
    Atlanta Fulfilment Centre  | Fine Knit Cashmere Scarf              | CO-10190-CAME      | Camel           |                2 |              0.0 |                      2 |                    2927
    (50 rows)
  6. What came of it

    The memo and the queries that followed; links found by title, so inferred

    It builds on:

  7. It becomes benchmark query q394

    Changed only where the benchmark needs the same result on every system

    • spellingfetch first
    • spellingdate cast
    • determinismtie-breaker: complete the group key
    • numericsdocs/NUMERICS.md: rounding removed; results keep full precision
    • made explicita selected t.col gets AS col, its standard name made explicit (8×)
    • determinismthe standard leaves the place of NULLs in a sort to the implementation: NULLS LAST ascending, NULLS FIRST descending, as in the reference results (5×)
    • placeholderfetch first
    The benchmark text, against the submitted SQL
    WITH three_warehouses AS (  SELECT id, name FROM warehouses  WHERE name IN ('Atlanta Fulfilment Centre','Reading Fulfilment Centre','Den Haag Fulfilment Centre')),adjustments AS (  SELECT sa.variant_id, sa.reason, sa.created_at, w.name AS warehouse_name  SELECT sa.variant_id AS variant_id, sa.reason AS reason, sa.created_at AS created_at, w.name AS warehouse_name  FROM stock_adjustments sa  JOIN stock_locations sl ON sl.id = sa.stock_location_id  JOIN three_warehouses w ON w.id = sl.warehouse_id  WHERE sa.created_at >= DATE '2025-01-01' AND sa.created_at < DATE '2026-01-01'),variant_info AS (  SELECT pv.id AS variant_id, pv.sku, pv.name AS variant_name, p.name AS product_name  SELECT pv.id AS variant_id, pv.sku AS sku, pv.name AS variant_name, p.name AS product_name  FROM product_variants pv  JOIN products p ON p.id = pv.product_id),aggregated AS (  SELECT    a.warehouse_name,    vi.product_name,    vi.sku,    vi.variant_name,    a.warehouse_name AS warehouse_name,    vi.product_name AS product_name,    vi.sku AS sku,    vi.variant_name AS variant_name,    COUNT(*) AS adjustment_count,    ROUND(100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_theft_reason,    COUNT(DISTINCT DATE(a.created_at)) AS distinct_days_affected    100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*) AS pct_theft_reason,    COUNT(DISTINCT CAST(a.created_at AS DATE)) AS distinct_days_affected  FROM adjustments a  JOIN variant_info vi ON vi.variant_id = a.variant_id  GROUP BY a.warehouse_name, vi.product_name, vi.sku, vi.variant_name)SELECT  warehouse_name,  product_name,  sku,  variant_name,  adjustment_count,  pct_theft_reason,  distinct_days_affected,  COUNT(*) OVER () AS total_distinct_variantsFROM aggregatedORDER BY adjustment_count DESC, warehouse_name ASC, sku ASCLIMIT 50ORDER BY adjustment_count DESC NULLS FIRST, warehouse_name ASC NULLS LAST, sku ASC NULLS LAST, product_name ASC NULLS LAST, variant_name ASC NULLS LAST{{fetch_first(50)}}
    WITH three_warehouses AS (
      SELECT id, name FROM warehouses
      WHERE name IN ('Atlanta Fulfilment Centre','Reading Fulfilment Centre','Den Haag Fulfilment Centre')
    ),
    adjustments AS (
      SELECT sa.variant_id AS variant_id, sa.reason AS reason, sa.created_at AS created_at, w.name AS warehouse_name
      FROM stock_adjustments sa
      JOIN stock_locations sl ON sl.id = sa.stock_location_id
      JOIN three_warehouses w ON w.id = sl.warehouse_id
      WHERE sa.created_at >= DATE '2025-01-01' AND sa.created_at < DATE '2026-01-01'
    ),
    variant_info AS (
      SELECT pv.id AS variant_id, pv.sku AS sku, pv.name AS variant_name, p.name AS product_name
      FROM product_variants pv
      JOIN products p ON p.id = pv.product_id
    ),
    aggregated AS (
      SELECT
        a.warehouse_name AS warehouse_name,
        vi.product_name AS product_name,
        vi.sku AS sku,
        vi.variant_name AS variant_name,
        COUNT(*) AS adjustment_count,
        100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*) AS pct_theft_reason,
        COUNT(DISTINCT CAST(a.created_at AS DATE)) AS distinct_days_affected
      FROM adjustments a
      JOIN variant_info vi ON vi.variant_id = a.variant_id
      GROUP BY a.warehouse_name, vi.product_name, vi.sku, vi.variant_name
    )
    SELECT
      warehouse_name,
      product_name,
      sku,
      variant_name,
      adjustment_count,
      pct_theft_reason,
      distinct_days_affected,
      COUNT(*) OVER () AS total_distinct_variants
    FROM aggregated
    ORDER BY adjustment_count DESC NULLS FIRST, warehouse_name ASC NULLS LAST, sku ASC NULLS LAST, product_name ASC NULLS LAST, variant_name ASC NULLS LAST
    FETCH FIRST 50 ROWS ONLY
    1 ms10 ms100 msHyper5.9 msDuckDB30.1 msGizmoSQL30.7 msclickhouse_brew94.8 msFirebolt29.7 msDataFusion31.6 msClickHouse14.1 ms
  8. Everything, as recorded

    The agents' own records, as the role play wrote them; only the personal data of the person who ran it is redacted

    Grace's whole session, 7 turns
    • The request, as Grace received it
      Report request from Fatima Zahra (analyst for the Director of Fulfilment Operations):
      
      Title: Which specific products drive discrepancies at the three standout apparel sites
      Question: At Atlanta (Cragsley Outfitters), Reading (Marrowby & Vane) and Den Haag (Studio Vrij) — the three sites with by far the most stock-count discrepancies — is the problem spread across the catalog, or concentrated in a handful of specific products/size-color variants?
      Grain: product variant, restricted to stock_adjustments rows at these three specific warehouses in 2025: Atlanta Fulfilment Centre, Reading Fulfilment Centre, Den Haag Fulfilment Centre
      Columns:
      - warehouse_name
      - product_name
      - sku
      - variant_name (product_variants.name, which typically encodes size/color)
      - adjustment_count (count of stock_adjustments rows for this variant at this warehouse)
      - pct_theft_reason (% of this variant's adjustments at this warehouse tagged 'Missing - suspected theft', rounded 1dp)
      - distinct_days_affected (count of distinct calendar dates with >=1 adjustment for this variant at this warehouse)
      Details: Source: stock_adjustments, created_at between 2025-01-01 and 2025-12-31 (half-open bound), joined to stock_locations (filtered to the 3 named warehouses by name) and to product_variants (via variant_id) and products (for product_name). Group by warehouse, product, sku, variant_name. Order by adjustment_count descending, tie-break by warehouse_name, then sku. Cap at 50 rows and note the total distinct variant count even if it exceeds 50.
      
      Check your query with the warehouse's dry_run tool, then hand it in with submit.
    • Grace calls dry_run
      WITH three_warehouses AS (
        SELECT id, name FROM warehouses
        WHERE name IN ('Atlanta Fulfilment Centre','Reading Fulfilment Centre','Den Haag Fulfilment Centre')
      ),
      adjustments AS (
        SELECT sa.variant_id, sa.reason, sa.created_at, w.name AS warehouse_name
        FROM stock_adjustments sa
        JOIN stock_locations sl ON sl.id = sa.stock_location_id
        JOIN three_warehouses w ON w.id = sl.warehouse_id
        WHERE sa.created_at >= DATE '2025-01-01' AND sa.created_at < DATE '2026-01-01'
      ),
      variant_info AS (
        SELECT pv.id AS variant_id, pv.sku, pv.name AS variant_name, p.name AS product_name
        FROM product_variants pv
        JOIN products p ON p.id = pv.product_id
      ),
      aggregated AS (
        SELECT
          a.warehouse_name,
          vi.product_name,
          vi.sku,
          vi.variant_name,
          COUNT(*) AS adjustment_count,
          ROUND(100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_theft_reason,
          COUNT(DISTINCT DATE(a.created_at)) AS distinct_days_affected
        FROM adjustments a
        JOIN variant_info vi ON vi.variant_id = a.variant_id
        GROUP BY a.warehouse_name, vi.product_name, vi.sku, vi.variant_name
      )
      SELECT
        warehouse_name,
        product_name,
        sku,
        variant_name,
        adjustment_count,
        pct_theft_reason,
        distinct_days_affected,
        COUNT(*) OVER () AS total_distinct_variants
      FROM aggregated
      ORDER BY adjustment_count DESC, warehouse_name ASC, sku ASC
      LIMIT 50
    • The warehouse answers
      STATUS: COMPILES (dry run on the empty schema, no data read)
      COLUMNS: warehouse_name, product_name, sku, variant_name, adjustment_count, pct_theft_reason, distinct_days_affected, total_distinct_variants
    • GraceLooks good. Submitting.
    • Grace calls submit
      WITH three_warehouses AS (
        SELECT id, name FROM warehouses
        WHERE name IN ('Atlanta Fulfilment Centre','Reading Fulfilment Centre','Den Haag Fulfilment Centre')
      ),
      adjustments AS (
        SELECT sa.variant_id, sa.reason, sa.created_at, w.name AS warehouse_name
        FROM stock_adjustments sa
        JOIN stock_locations sl ON sl.id = sa.stock_location_id
        JOIN three_warehouses w ON w.id = sl.warehouse_id
        WHERE sa.created_at >= DATE '2025-01-01' AND sa.created_at < DATE '2026-01-01'
      ),
      variant_info AS (
        SELECT pv.id AS variant_id, pv.sku, pv.name AS variant_name, p.name AS product_name
        FROM product_variants pv
        JOIN products p ON p.id = pv.product_id
      ),
      aggregated AS (
        SELECT
          a.warehouse_name,
          vi.product_name,
          vi.sku,
          vi.variant_name,
          COUNT(*) AS adjustment_count,
          ROUND(100.0 * SUM(CASE WHEN a.reason = 'Missing - suspected theft' THEN 1 ELSE 0 END) / COUNT(*), 1) AS pct_theft_reason,
          COUNT(DISTINCT DATE(a.created_at)) AS distinct_days_affected
        FROM adjustments a
        JOIN variant_info vi ON vi.variant_id = a.variant_id
        GROUP BY a.warehouse_name, vi.product_name, vi.sku, vi.variant_name
      )
      SELECT
        warehouse_name,
        product_name,
        sku,
        variant_name,
        adjustment_count,
        pct_theft_reason,
        distinct_days_affected,
        COUNT(*) OVER () AS total_distinct_variants
      FROM aggregated
      ORDER BY adjustment_count DESC, warehouse_name ASC, sku ASC
      LIMIT 50
    • The warehouse answers
      Submitted to tonight's batch. Your work on this request is done.
    • GraceSubmitted. Summary of what the query does: - **Scope**: `stock_adjustments` in 2025 (`created_at` in `[2025-01-01, 2026-01-01)`), restricted to the three named warehouses via `stock_locations → warehouses`. - **Grain**: one row per warehouse × product variant, joining `product_variants` → `products` for names/SKU. - **Measures**: `adjustment_count` (row count), `pct_theft_reason` (share tagged `'Missing - suspected theft'`, 1dp), `distinct_days_affected` (distinct calendar dates with ≥1 adjustment). - **Ordering/cap**: sorted by `adjustment_count` desc, then `warehouse_name`, then `sku`; capped at 50 rows via `LIMIT 50`. - **Extra**: added `total_distinct_variants`, a window-function count of all qualifying variant rows (computed before the cap), so the printed report also shows how many variants total had discrepancies even though only the top 50 are listed — flagged this addition in the submit note.