DB Olympics

Queries · q188 · Director of Fulfilment Operations · week 1, night 2

Stock-count discrepancies by storage-location kind, company-wide

“Across the whole company (not just the top warehouses by value), does the cycle-count mismatch concentrate in pick locations specifically, or do other location kinds (bulk, overflow, etc.) also carry meaningful discrepancy volume?”

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 SQLInesThinks in window functions: ranks, running totals, LAG/LEAD for comparisons, percent-of-total.

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 1

    Subject: Inventory accuracy — what I need for Friday's memo

    Fatima,

    Tobias and I need to give the auditors (and our bigger merchants) a credible answer on how trustworthy our stock numbers are, where it breaks down, and whether it's getting better or worse. This feeds the joint audit response and will likely shape where we invest in warehouse process fixes next quarter — so I'd rather have three sharp answers than ten partial ones. Please use your nightly slots on these, in rough priority order:

    1. How big is the gap between what we think we have and what's actually there? Across our warehouses, how often do physical counts come back different from the stock we had on record, and how large are those differences in units (and ideally value)? I want a sense of scale before anything else.
    2. Where is it worst? Does the mismatch concentrate in particular warehouses, or particular kinds of storage locations (e.g. bulk shelving vs. pick bins)? If a handful of sites or location types account for most of the problem, that tells us where to send help first.
    3. Is it a product or a process problem? Are the discrepancies spread evenly across products, or concentrated in certain categories, high-velocity items, or items we handle in lots/serials? This will tell Tobias and me whether this is a handling issue or a tracking-method issue.
    4. Are our "soft holds" on stock reliable? When we reserve stock for an order, does that reservation actually get fulfilled as expected, or do we see a lot of stuck/expired holds that quietly overstate what's available to sell? This matters for whether we're overpromising stock to customers.
    5. Is this getting better or worse over time? A simple trend over the last several months would tell us whether recent process changes are helping or whether the problem is growing — useful context for the auditors either way.

    If you can only get to three this week, do 1, 2 and 3 — those are the ones Tobias and I will lean on most heavily in the audit conversation. Happy to talk through trade-offs before you lock in Monday night's requests.

    Thanks, Tomasz

    A note from the Chief Financial Officer, Tobias Lindqvist

    Subject: Finance questions for the inventory accuracy review

    Hi Fatima,

    A few things from the finance side as you dig into this with Tomasz:

    1. Do stock discrepancies cluster around particular merchants or warehouses in a way that could point to a write-off or valuation exposure we need to flag in the annual accounts?
    2. When counts don't match recorded stock, is it skewed more toward unexplained losses (shrinkage) versus unexplained gains — and has that pattern shifted over the year? That matters for how we size a shrinkage provision.
    3. Are the mismatches concentrated in slower-moving or higher-value goods, or spread evenly? That shapes how material this is for the merchants we'd flag to auditors.

    Keep it high level for now — happy to go deeper once you have an initial read.

    Thanks, Tobias

  3. Fatima Zahra plans the night

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

    Reading night 1 critically, two things jump out before I trust the headline numbers, plus one new question worth opening.

    (1) Suspicious invariant: in report 1, abs_units_variance equals cycle_count_events exactly in every single month (e.g. Jan 764=764), and avg_abs_units_per_event is 1.0 in all 12 months. Report 3 shows the same identity for every one of 105 categories (Bikes 102=102, Tops 1086=1086, etc). That means every recorded cycle-count discrepancy is off by exactly one unit, with zero variation — never 2, never 5. That's either a real and important finding (our "size of discrepancy" story is really a "frequency of single-unit misses" story, which changes the materiality narrative for Tobias) or a sign that stock_movements.quantity isn't what I think it is for this kind. I want to verify this against other movement kinds before I put it in the memo as fact.

    (2) Report 2's top 50 rows (ranked by value) are all location_kind='pick' — not one bulk/overflow/other row appears. That's a strong concentration signal for Tomasz's "particular kinds of storage locations" question, but I need a company-wide total by location_kind (not filtered to top-50-by-warehouse) to confirm it isn't just pick locations dominating the value ranking while other kinds still carry meaningful event counts further down the list.

    (3) Tomasz's Q4 (reservation reliability) hasn't been touched yet. With two slots going to validate/sharpen findings 1 and 2 above, I have a free slot to open Q4 tonight rather than wait, since nights 3-4 will still be needed for deeper drill-down and the trend view (Q5).

    Tonight's three requests: (A) movement-magnitude distribution by kind, to sanity-check the ±1 pattern and see if 'adjustment'-kind movements (a different, less formal correction path) carry larger swings; (B) a clean location-kind-only rollup (not crossed with warehouse) so kinds with little/no cycle-count activity are visible as explicit zero/low rows; (C) a first read on stock reservation reliability — how often holds are released normally vs. left stuck past their expiry, which overstates sellable availability.

    Stock-count discrepancies by storage-location kind, company-wide
    Question
    Across the whole company (not just the top warehouses by value), does the cycle-count mismatch concentrate in pick locations specifically, or do other location kinds (bulk, overflow, etc.) also carry meaningful discrepancy volume?
    One row per
    stock_locations.kind
    Columns
    • location_kind
    • distinct_locations_with_activity (count of distinct stock_location_id with >=1 cycle_count event in the window)
    • total_locations_of_this_kind (count of distinct stock_location_id of this kind that exist at all, active or not)
    • cycle_count_events
    • abs_units_variance
    • net_units_variance (signed; negative = net shrinkage)
    • estimated_value_eur (same costing/FX method as night 1: preferred-then-cheapest supplier_products.unit_cost, converted to EUR via exchange_rates on the movement's occurred_at date)
    • share_of_total_value_pct
  4. Ines 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 kinds AS (
      SELECT DISTINCT kind AS location_kind
      FROM stock_locations
    ),
    location_counts AS (
      SELECT kind AS location_kind,
             COUNT(DISTINCT id) AS total_locations_of_this_kind
      FROM stock_locations
      GROUP BY kind
    ),
    cycle_counts AS (
      SELECT sl.kind AS location_kind,
             sm.stock_location_id,
             sm.variant_id,
             sm.quantity,
             sm.occurred_at
      FROM stock_movements sm
      JOIN stock_locations sl ON sl.id = sm.stock_location_id
      WHERE sm.kind = 'cycle_count'
        AND sm.occurred_at >= TIMESTAMP '2025-01-01'
        AND sm.occurred_at < TIMESTAMP '2026-01-01'
    ),
    variant_cost AS (
      SELECT variant_id, unit_cost, currency_code
      FROM (
        SELECT variant_id, unit_cost, currency_code,
               ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC, unit_cost ASC) AS rn
        FROM supplier_products
        WHERE unit_cost IS NOT NULL
      ) ranked
      WHERE rn = 1
    ),
    valued AS (
      SELECT cc.location_kind,
             cc.stock_location_id,
             cc.quantity,
             CASE
               WHEN vc.unit_cost IS NOT NULL AND er.rate IS NOT NULL
               THEN ABS(cc.quantity) * vc.unit_cost / er.rate
               ELSE 0
             END AS value_eur
      FROM cycle_counts cc
      LEFT JOIN variant_cost vc ON vc.variant_id = cc.variant_id
      LEFT JOIN exchange_rates er
        ON er.base_code = 'EUR'
       AND er.quote_code = vc.currency_code
       AND er.as_of = CAST(cc.occurred_at AS date)
    ),
    agg AS (
      SELECT location_kind,
             COUNT(DISTINCT stock_location_id) AS distinct_locations_with_activity,
             COUNT(*) AS cycle_count_events,
             SUM(ABS(quantity)) AS abs_units_variance,
             SUM(quantity) AS net_units_variance,
             SUM(value_eur) AS estimated_value_eur
      FROM valued
      GROUP BY location_kind
    )
    SELECT
      k.location_kind,
      COALESCE(a.distinct_locations_with_activity, 0) AS distinct_locations_with_activity,
      COALESCE(lc.total_locations_of_this_kind, 0) AS total_locations_of_this_kind,
      COALESCE(a.cycle_count_events, 0) AS cycle_count_events,
      COALESCE(a.abs_units_variance, 0) AS abs_units_variance,
      COALESCE(a.net_units_variance, 0) AS net_units_variance,
      ROUND(COALESCE(a.estimated_value_eur, 0), 2) AS estimated_value_eur,
      ROUND(
        100.0 * COALESCE(a.estimated_value_eur, 0)
        / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0),
        2
      ) AS share_of_total_value_pct
    FROM kinds k
    LEFT JOIN location_counts lc ON lc.location_kind = k.location_kind
    LEFT JOIN agg a ON a.location_kind = k.location_kind
    ORDER BY COALESCE(a.estimated_value_eur, 0) DESC, k.location_kind ASC

    “The query compiles and returns the requested columns. 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 the approach: - Grain: one row per stock_locations.kind, built from the full distinct set of kinds (so zero-activity kinds still show up via LEFT JOIN). - Activity window: stock_movements with kind = 'cycle_count' and occurred_at in 2025. - Costing: preferred-then-cheapest supplier_products.unit_cost per variant (ROW_NUMBER ordered by is_preferred DESC, unit_cost ASC), converted to EUR using exchange_rates (base EUR) matched on the movement's own date. - Value measure: estimated_value_eur is based on absolute unit variance (|quantity| × cost), since the question is about discrepancy volume, not net direction — net direction is still shown separately via net_units_variance. - Rows missing a cost or exchange rate contribute 0 to value rather than being dropped, so counts/events still reflect all activity.”

  5. The report comes back overnight

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

    location_kind | distinct_locations_with_activity | total_locations_of_this_kind | cycle_count_events | abs_units_variance | net_units_variance | estimated_value_eur | share_of_total_value_pct
    --------------+----------------------------------+------------------------------+--------------------+--------------------+--------------------+---------------------+-------------------------
    pick          |                              120 |                          157 |              10193 |              10193 |              -3879 |           262456.85 |                    100.0
    bulk          |                                0 |                          157 |                  0 |                  0 |                  0 |                 0.0 |                      0.0
    returns       |                                0 |                          157 |                  0 |                  0 |                  0 |                 0.0 |                      0.0
    (3 rows)
  6. What came of it

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

    Later queries that build on this report:

    It builds on:

  7. It becomes benchmark query q188

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

    • determinismtie-breaker: (supplier_id, variant_id) is unique, so supplier_id is unique within the variant partition
    • numericsdocs/NUMERICS.md: rounding removed; results keep full precision
    • numericsdocs/NUMERICS.md: x / exchange rate cast to NUMERIC(18,6)
    • 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×)
    The benchmark text, against the submitted SQL
    WITH kinds AS (  SELECT DISTINCT kind AS location_kind  FROM stock_locations),location_counts AS (  SELECT kind AS location_kind,         COUNT(DISTINCT id) AS total_locations_of_this_kind  FROM stock_locations  GROUP BY kind),cycle_counts AS (  SELECT sl.kind AS location_kind,         sm.stock_location_id,         sm.variant_id,         sm.quantity,         sm.occurred_at         sm.stock_location_id AS stock_location_id,         sm.variant_id AS variant_id,         sm.quantity AS quantity,         sm.occurred_at AS occurred_at  FROM stock_movements sm  JOIN stock_locations sl ON sl.id = sm.stock_location_id  WHERE sm.kind = 'cycle_count'    AND sm.occurred_at >= TIMESTAMP '2025-01-01'    AND sm.occurred_at < TIMESTAMP '2026-01-01'),variant_cost AS (  SELECT variant_id, unit_cost, currency_code  FROM (    SELECT variant_id, unit_cost, currency_code,           ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC, unit_cost ASC) AS rn           ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC NULLS FIRST, unit_cost ASC NULLS LAST, supplier_id NULLS LAST) AS rn    FROM supplier_products    WHERE unit_cost IS NOT NULL  ) ranked  WHERE rn = 1),valued AS (  SELECT cc.location_kind,         cc.stock_location_id,         cc.quantity,  SELECT cc.location_kind AS location_kind,         cc.stock_location_id AS stock_location_id,         cc.quantity AS quantity,         CASE           WHEN vc.unit_cost IS NOT NULL AND er.rate IS NOT NULL           THEN ABS(cc.quantity) * vc.unit_cost / er.rate           THEN CAST(ABS(cc.quantity) * vc.unit_cost / er.rate AS NUMERIC(18,6))           ELSE 0         END AS value_eur  FROM cycle_counts cc  LEFT JOIN variant_cost vc ON vc.variant_id = cc.variant_id  LEFT JOIN exchange_rates er    ON er.base_code = 'EUR'   AND er.quote_code = vc.currency_code   AND er.as_of = CAST(cc.occurred_at AS date)),agg AS (  SELECT location_kind,         COUNT(DISTINCT stock_location_id) AS distinct_locations_with_activity,         COUNT(*) AS cycle_count_events,         SUM(ABS(quantity)) AS abs_units_variance,         SUM(quantity) AS net_units_variance,         SUM(value_eur) AS estimated_value_eur  FROM valued  GROUP BY location_kind)SELECT  k.location_kind,  k.location_kind AS location_kind,  COALESCE(a.distinct_locations_with_activity, 0) AS distinct_locations_with_activity,  COALESCE(lc.total_locations_of_this_kind, 0) AS total_locations_of_this_kind,  COALESCE(a.cycle_count_events, 0) AS cycle_count_events,  COALESCE(a.abs_units_variance, 0) AS abs_units_variance,  COALESCE(a.net_units_variance, 0) AS net_units_variance,  ROUND(COALESCE(a.estimated_value_eur, 0), 2) AS estimated_value_eur,  ROUND(    100.0 * COALESCE(a.estimated_value_eur, 0)    / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0),    2  ) AS share_of_total_value_pct  COALESCE(a.estimated_value_eur, 0) AS estimated_value_eur,  100.0 * COALESCE(a.estimated_value_eur, 0)  / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0) AS share_of_total_value_pctFROM kinds kLEFT JOIN location_counts lc ON lc.location_kind = k.location_kindLEFT JOIN agg a ON a.location_kind = k.location_kindORDER BY COALESCE(a.estimated_value_eur, 0) DESC, k.location_kind ASCORDER BY COALESCE(a.estimated_value_eur, 0) DESC NULLS FIRST, k.location_kind ASC NULLS LAST
    WITH kinds AS (
      SELECT DISTINCT kind AS location_kind
      FROM stock_locations
    ),
    location_counts AS (
      SELECT kind AS location_kind,
             COUNT(DISTINCT id) AS total_locations_of_this_kind
      FROM stock_locations
      GROUP BY kind
    ),
    cycle_counts AS (
      SELECT sl.kind AS location_kind,
             sm.stock_location_id AS stock_location_id,
             sm.variant_id AS variant_id,
             sm.quantity AS quantity,
             sm.occurred_at AS occurred_at
      FROM stock_movements sm
      JOIN stock_locations sl ON sl.id = sm.stock_location_id
      WHERE sm.kind = 'cycle_count'
        AND sm.occurred_at >= TIMESTAMP '2025-01-01'
        AND sm.occurred_at < TIMESTAMP '2026-01-01'
    ),
    variant_cost AS (
      SELECT variant_id, unit_cost, currency_code
      FROM (
        SELECT variant_id, unit_cost, currency_code,
               ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC NULLS FIRST, unit_cost ASC NULLS LAST, supplier_id NULLS LAST) AS rn
        FROM supplier_products
        WHERE unit_cost IS NOT NULL
      ) ranked
      WHERE rn = 1
    ),
    valued AS (
      SELECT cc.location_kind AS location_kind,
             cc.stock_location_id AS stock_location_id,
             cc.quantity AS quantity,
             CASE
               WHEN vc.unit_cost IS NOT NULL AND er.rate IS NOT NULL
               THEN CAST(ABS(cc.quantity) * vc.unit_cost / er.rate AS NUMERIC(18,6))
               ELSE 0
             END AS value_eur
      FROM cycle_counts cc
      LEFT JOIN variant_cost vc ON vc.variant_id = cc.variant_id
      LEFT JOIN exchange_rates er
        ON er.base_code = 'EUR'
       AND er.quote_code = vc.currency_code
       AND er.as_of = CAST(cc.occurred_at AS date)
    ),
    agg AS (
      SELECT location_kind,
             COUNT(DISTINCT stock_location_id) AS distinct_locations_with_activity,
             COUNT(*) AS cycle_count_events,
             SUM(ABS(quantity)) AS abs_units_variance,
             SUM(quantity) AS net_units_variance,
             SUM(value_eur) AS estimated_value_eur
      FROM valued
      GROUP BY location_kind
    )
    SELECT
      k.location_kind AS location_kind,
      COALESCE(a.distinct_locations_with_activity, 0) AS distinct_locations_with_activity,
      COALESCE(lc.total_locations_of_this_kind, 0) AS total_locations_of_this_kind,
      COALESCE(a.cycle_count_events, 0) AS cycle_count_events,
      COALESCE(a.abs_units_variance, 0) AS abs_units_variance,
      COALESCE(a.net_units_variance, 0) AS net_units_variance,
      COALESCE(a.estimated_value_eur, 0) AS estimated_value_eur,
      100.0 * COALESCE(a.estimated_value_eur, 0)
      / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0) AS share_of_total_value_pct
    FROM kinds k
    LEFT JOIN location_counts lc ON lc.location_kind = k.location_kind
    LEFT JOIN agg a ON a.location_kind = k.location_kind
    ORDER BY COALESCE(a.estimated_value_eur, 0) DESC NULLS FIRST, k.location_kind ASC NULLS LAST
    100 ms1 sHyper163 msDuckDB136 msGizmoSQL132 msclickhouse_brew183 msFirebolterrorDataFusion572 msClickHouseerror
    • Firebolt{ "errors": [ { "description": "Line 39, Column 54: Operations between decimals with different precision and scale is not supported at the moment. Explicitly cast one of the decimals to other decimal precision and scale." } ], "query": { "query_id": "fc79d9bb-38ce-41fb-be0e-be5961373d56", "query_lab
    • ClickHouseCode: 69. DB::Exception: Decimal result's scale is less than argument's one: while executing function divide on arguments multiply(abs(__table7.quantity), __table10.unit_cost) Nullable(Decimal(14, 4)) Nullable(size = 0, Decimal64(size = 0), UInt8(size = 0)), __table13.rate Nullable(Decimal(12, 6)) N
  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

    Ines's whole session, 7 turns
    • The request, as Ines received it
      Report request from Fatima Zahra (analyst for the Director of Fulfilment Operations):
      
      Title: Stock-count discrepancies by storage-location kind, company-wide
      Question: Across the whole company (not just the top warehouses by value), does the cycle-count mismatch concentrate in pick locations specifically, or do other location kinds (bulk, overflow, etc.) also carry meaningful discrepancy volume?
      Grain: stock_locations.kind
      Columns:
      - location_kind
      - distinct_locations_with_activity (count of distinct stock_location_id with >=1 cycle_count event in the window)
      - total_locations_of_this_kind (count of distinct stock_location_id of this kind that exist at all, active or not)
      - cycle_count_events
      - abs_units_variance
      - net_units_variance (signed; negative = net shrinkage)
      - estimated_value_eur (same costing/FX method as night 1: preferred-then-cheapest supplier_products.unit_cost, converted to EUR via exchange_rates on the movement's occurred_at date)
      - share_of_total_value_pct
      Details: Start from the full set of distinct stock_locations.kind values across all tenants (so a kind with zero cycle_count activity still appears as a row with 0s, via LEFT JOIN — do not just omit kinds with no matches). Then LEFT JOIN stock_movements where kind='cycle_count' and occurred_at between 2025-01-01 and 2025-12-31 on stock_location_id, aggregating per stock_locations.kind. total_locations_of_this_kind should count all stock_locations rows of that kind regardless of activity, to show how much of the location base is even generating cycle counts. Order by estimated_value_eur descending, tie-break by location_kind.
      
      Check your query with the warehouse's dry_run tool, then hand it in with submit.
    • Ines calls dry_run
      WITH kinds AS (
        SELECT DISTINCT kind AS location_kind
        FROM stock_locations
      ),
      location_counts AS (
        SELECT kind AS location_kind,
               COUNT(DISTINCT id) AS total_locations_of_this_kind
        FROM stock_locations
        GROUP BY kind
      ),
      cycle_counts AS (
        SELECT sl.kind AS location_kind,
               sm.stock_location_id,
               sm.variant_id,
               sm.quantity,
               sm.occurred_at
        FROM stock_movements sm
        JOIN stock_locations sl ON sl.id = sm.stock_location_id
        WHERE sm.kind = 'cycle_count'
          AND sm.occurred_at >= TIMESTAMP '2025-01-01'
          AND sm.occurred_at < TIMESTAMP '2026-01-01'
      ),
      variant_cost AS (
        SELECT variant_id, unit_cost, currency_code
        FROM (
          SELECT variant_id, unit_cost, currency_code,
                 ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC, unit_cost ASC) AS rn
          FROM supplier_products
          WHERE unit_cost IS NOT NULL
        ) ranked
        WHERE rn = 1
      ),
      valued AS (
        SELECT cc.location_kind,
               cc.stock_location_id,
               cc.quantity,
               CASE
                 WHEN vc.unit_cost IS NOT NULL AND er.rate IS NOT NULL
                 THEN ABS(cc.quantity) * vc.unit_cost / er.rate
                 ELSE 0
               END AS value_eur
        FROM cycle_counts cc
        LEFT JOIN variant_cost vc ON vc.variant_id = cc.variant_id
        LEFT JOIN exchange_rates er
          ON er.base_code = 'EUR'
         AND er.quote_code = vc.currency_code
         AND er.as_of = CAST(cc.occurred_at AS date)
      ),
      agg AS (
        SELECT location_kind,
               COUNT(DISTINCT stock_location_id) AS distinct_locations_with_activity,
               COUNT(*) AS cycle_count_events,
               SUM(ABS(quantity)) AS abs_units_variance,
               SUM(quantity) AS net_units_variance,
               SUM(value_eur) AS estimated_value_eur
        FROM valued
        GROUP BY location_kind
      )
      SELECT
        k.location_kind,
        COALESCE(a.distinct_locations_with_activity, 0) AS distinct_locations_with_activity,
        COALESCE(lc.total_locations_of_this_kind, 0) AS total_locations_of_this_kind,
        COALESCE(a.cycle_count_events, 0) AS cycle_count_events,
        COALESCE(a.abs_units_variance, 0) AS abs_units_variance,
        COALESCE(a.net_units_variance, 0) AS net_units_variance,
        ROUND(COALESCE(a.estimated_value_eur, 0), 2) AS estimated_value_eur,
        ROUND(
          100.0 * COALESCE(a.estimated_value_eur, 0)
          / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0),
          2
        ) AS share_of_total_value_pct
      FROM kinds k
      LEFT JOIN location_counts lc ON lc.location_kind = k.location_kind
      LEFT JOIN agg a ON a.location_kind = k.location_kind
      ORDER BY COALESCE(a.estimated_value_eur, 0) DESC, k.location_kind ASC
    • The warehouse answers
      STATUS: COMPILES (dry run on the empty schema, no data read)
      COLUMNS: location_kind, distinct_locations_with_activity, total_locations_of_this_kind, cycle_count_events, abs_units_variance, net_units_variance, estimated_value_eur, share_of_total_value_pct
    • InesThe query compiles and returns the requested columns. Submitting.
    • Ines calls submit
      WITH kinds AS (
        SELECT DISTINCT kind AS location_kind
        FROM stock_locations
      ),
      location_counts AS (
        SELECT kind AS location_kind,
               COUNT(DISTINCT id) AS total_locations_of_this_kind
        FROM stock_locations
        GROUP BY kind
      ),
      cycle_counts AS (
        SELECT sl.kind AS location_kind,
               sm.stock_location_id,
               sm.variant_id,
               sm.quantity,
               sm.occurred_at
        FROM stock_movements sm
        JOIN stock_locations sl ON sl.id = sm.stock_location_id
        WHERE sm.kind = 'cycle_count'
          AND sm.occurred_at >= TIMESTAMP '2025-01-01'
          AND sm.occurred_at < TIMESTAMP '2026-01-01'
      ),
      variant_cost AS (
        SELECT variant_id, unit_cost, currency_code
        FROM (
          SELECT variant_id, unit_cost, currency_code,
                 ROW_NUMBER() OVER (PARTITION BY variant_id ORDER BY is_preferred DESC, unit_cost ASC) AS rn
          FROM supplier_products
          WHERE unit_cost IS NOT NULL
        ) ranked
        WHERE rn = 1
      ),
      valued AS (
        SELECT cc.location_kind,
               cc.stock_location_id,
               cc.quantity,
               CASE
                 WHEN vc.unit_cost IS NOT NULL AND er.rate IS NOT NULL
                 THEN ABS(cc.quantity) * vc.unit_cost / er.rate
                 ELSE 0
               END AS value_eur
        FROM cycle_counts cc
        LEFT JOIN variant_cost vc ON vc.variant_id = cc.variant_id
        LEFT JOIN exchange_rates er
          ON er.base_code = 'EUR'
         AND er.quote_code = vc.currency_code
         AND er.as_of = CAST(cc.occurred_at AS date)
      ),
      agg AS (
        SELECT location_kind,
               COUNT(DISTINCT stock_location_id) AS distinct_locations_with_activity,
               COUNT(*) AS cycle_count_events,
               SUM(ABS(quantity)) AS abs_units_variance,
               SUM(quantity) AS net_units_variance,
               SUM(value_eur) AS estimated_value_eur
        FROM valued
        GROUP BY location_kind
      )
      SELECT
        k.location_kind,
        COALESCE(a.distinct_locations_with_activity, 0) AS distinct_locations_with_activity,
        COALESCE(lc.total_locations_of_this_kind, 0) AS total_locations_of_this_kind,
        COALESCE(a.cycle_count_events, 0) AS cycle_count_events,
        COALESCE(a.abs_units_variance, 0) AS abs_units_variance,
        COALESCE(a.net_units_variance, 0) AS net_units_variance,
        ROUND(COALESCE(a.estimated_value_eur, 0), 2) AS estimated_value_eur,
        ROUND(
          100.0 * COALESCE(a.estimated_value_eur, 0)
          / NULLIF(SUM(COALESCE(a.estimated_value_eur, 0)) OVER (), 0),
          2
        ) AS share_of_total_value_pct
      FROM kinds k
      LEFT JOIN location_counts lc ON lc.location_kind = k.location_kind
      LEFT JOIN agg a ON a.location_kind = k.location_kind
      ORDER BY COALESCE(a.estimated_value_eur, 0) DESC, k.location_kind ASC
    • The warehouse answers
      Submitted to tonight's batch. Your work on this request is done.
    • InesSubmitted. Summary of the approach: - **Grain:** one row per `stock_locations.kind`, built from the full distinct set of kinds (so zero-activity kinds still show up via LEFT JOIN). - **Activity window:** `stock_movements` with `kind = 'cycle_count'` and `occurred_at` in 2025. - **Costing:** preferred-then-cheapest `supplier_products.unit_cost` per variant (ROW_NUMBER ordered by `is_preferred DESC, unit_cost ASC`), converted to EUR using `exchange_rates` (base `EUR`) matched on the movement's own date. - **Value measure:** `estimated_value_eur` is based on absolute unit variance (`|quantity| × cost`), since the question is about discrepancy volume, not net direction — net direction is still shown separately via `net_units_variance`. - Rows missing a cost or exchange rate contribute 0 to value rather than being dropped, so counts/events still reflect all activity.