Which stores are slipping?: the code

These are the files that do most of the work. The comments explain why each part works the way it does. If anything is unclear, or you would do it differently, tell me. I will also send you the full code for free, with nothing to sign up for. Ask for the full code

sql/01-clean.sql

The cleaning. One DISTINCT removes the repeated rows, and one CASE joins categories published under two spellings. 24 lines

-- Step 1: clean the published rows into one table of order lines.
-- Runs against data/raw.sqlite with the clean database attached as "clean".

-- Exact copies: from late 2024 and again in late 2025 the file repeats whole rows two to four
-- times. Keeping one of each identical row removes them. source_file is left out of the match,
-- since a copy can sit in a different part file.
CREATE TABLE clean.lines AS
SELECT DISTINCT
  invoice_id,
  ordered_on,
  store_no,
  store_name,
  upper(trim(store_city)) AS store_city,
  upper(trim(county_name)) AS county,
  -- Two categories are each published under two spellings ("LIQUEURS" and "LIQUEUR").
  CASE WHEN category_name LIKE '%LIQUEUR' THEN category_name || 'S' ELSE category_name END AS category,
  item_no,
  im_desc AS item,
  CAST(pack AS INTEGER) AS pack,
  CAST(bottle_volume_ml AS INTEGER) AS bottle_ml,
  CAST(sales_bottles AS INTEGER) AS bottles,
  CAST(sales_dollars AS REAL) AS dollars,
  CAST(sales_liters AS REAL) AS liters
FROM orders_raw;

sql/page/08-persistence.sql

The test of the ranking. It counts the stores in the bottom tenth in both halves, beside the one in ten that chance would keep. 18 lines

-- How many stores in the bottom tenth for the first half were still there in the second.
-- If the ranking were pure luck, one in ten of them would stay by chance.
WITH halves AS (
  SELECT store_no,
         sum(CASE WHEN half = '2025-H1' THEN dollars END) / sum(CASE WHEN half = '2024-H1' THEN dollars END) AS first_half,
         sum(CASE WHEN half = '2025-H2' THEN dollars END) / sum(CASE WHEN half = '2024-H2' THEN dollars END) AS second_half
  FROM sales JOIN stores USING (store_no)
  WHERE chain = :chain AND comparable = 1
  GROUP BY store_no
), ranked AS (
  SELECT ntile(10) OVER (ORDER BY first_half) AS first_tenth,
         ntile(10) OVER (ORDER BY second_half) AS second_tenth
  FROM halves
)
SELECT sum(first_tenth = 1) AS bottom_first_half,
       sum(first_tenth = 1 AND second_tenth = 1) AS bottom_both_halves,
       round(sum(first_tenth = 1) / 10.0, 1) AS expected_by_chance
FROM ranked;

src/site/worker.ts

Loads the database into SQLite in the browser and runs each query away from the page, so a slow one never freezes it. 41 lines

// Holds the database in a worker so a slow query never freezes the page.
import initSqlJs, { type Database } from "sql.js";
import wasmUrl from "sql.js/dist/sql-wasm.wasm?url";

type Request = { id: number; sql: string };
let db: Database | null = null;

async function open(): Promise<Database> {
  const SQL = await initSqlJs({ locateFile: () => wasmUrl });
  const res = await fetch("/data/iowa.sqlite.gz");
  if (!res.ok) throw new Error(`data ${res.status}`);
  let bytes = new Uint8Array(await res.arrayBuffer());
  // A host may already have undone the gzip in transit, so only unpack what still starts with its magic bytes.
  if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
    const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
    bytes = new Uint8Array(await new Response(stream).arrayBuffer());
  }
  return new SQL.Database(bytes);
}

const ready = open().then(
  (d) => {
    db = d;
    postMessage({ id: 0, ok: true, ready: true });
  },
  (err) => postMessage({ id: 0, ok: false, error: String(err) }),
);

onmessage = async (e: MessageEvent<Request>) => {
  await ready;
  const { id, sql } = e.data;
  if (!db) return postMessage({ id, ok: false, error: "The data did not load." });
  const t0 = performance.now();
  try {
    const results = db.exec(sql);
    const last = results.at(-1);
    postMessage({ id, ok: true, columns: last?.columns ?? [], rows: last?.values ?? [], ms: performance.now() - t0 });
  } catch (err) {
    postMessage({ id, ok: false, error: err instanceof Error ? err.message : String(err) });
  }
};