DB Olympics

Queries · q159 · Head of Pricing and Promotions · week 1, night 4

Concentration of refund cost on the two highest refund-to-discount-ratio instances

“For the two discount instances whose total refunds exceeded their own discount cost (Welcome 10% off with 260 orders, Volume tier 10+ with 104 orders, both from the prior return-rate report), is that refund cost driven by a handful of large refunds or spread broadly across many orders?”

Manager · asked the questionMarco BianchiHead of Pricing and Promotions. Previously in revenue management at a travel company.
Analyst · planned the reportOliver GrantPeer-minded: compares each merchant with peers of similar size and vertical.
Engineer · wrote the SQLOmarPragmatic: the shortest correct query, aggregates first and joins dimensions afterwards, FILTER clauses for conditional counts.

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 Head of Pricing and Promotions's desk

    Week 1; shared with Tobias Lindqvist, Chief Financial Officer

    Finance questions the cost of discounts. Which promotions and coupons brought additional sales, which only gave away margin, and is anything being misused?

  2. Marco Bianchi writes to Oliver Grant

    The manager, at the start of week 1

    Subject: Priorities for this week's discount cost-review with Tobias

    Oliver,

    Tobias and I need a credible answer to "are our promotions and coupons earning their keep," in time for Friday's memo. This feeds a joint decision on which promotions/coupons we keep, retire, or cap going into next quarter — so I'd rather have four solid, well-checked answers than a pile of rushed ones. Please pick the nights' reports accordingly and flag anything suspicious you find along the way rather than burying it in a footnote.

    Here's what I actually want to know, in my own words:

    1. Which promotions and coupons are costing us the most, and is that cost buying us anything? I want to see discount cost alongside the orders/revenue they sit on, so we can tell "big spend, big lift" apart from "big spend, no lift."
    2. For our top discounts, do customers actually spend more because of them, or are we just discounting purchases that would have happened anyway? I know this is the hard one — I just want our best honest read on it, even if approximate.
    3. Are any coupons being overused or abused — the same customers redeeming repeatedly, usage patterns that look like stacking or sharing of codes meant to be one-time or limited, or codes that are far outliving the campaign they were meant for?
    4. Which discounts are quietly eating into margin on top of their price reduction — for example cases where returns or refunds cluster around discounted orders, so the real cost is higher than the discount line alone suggests.
    5. (If there's a slot left) How does this differ by merchant or vertical — are one or two tenants responsible for most of the discount spend, which would change how we approach this.

    Keep each report to one clear question — I'd rather get three clean answers this week than one bundled one that gets bounced. Let's sync briefly before you submit Thursday's batch in case the first results change what we ask.

    Thanks, Marco

    A note from the Chief Financial Officer, Tobias Lindqvist

    Subject: Finance's angle on the promotions/coupons review

    Oliver,

    As you and Marco dig into discount performance this week, a few things I'd like the analysis to keep an eye on from the finance side:

    1. Are discounted orders actually incremental, or just margin we're giving away on sales that would have happened anyway? I care less about redemption volume and more about whether promotions are growing net revenue after the discount, versus simply lowering what we collect on existing demand.
    2. Is any of this exposed as cost we haven't fully absorbed yet? Where coupons stack with refunds or returns, I want to understand whether we're left carrying a loss after the fact, especially heading into year-end close.
    3. Is there any pattern of abuse or concentration — the same accounts or a narrow set of merchants repeatedly running the heaviest discounts — that's quietly eating into margin rather than driving genuine growth?

    Keep it tight; I mainly need the "so what" for the annual accounts and the 2026 budget assumptions on discount cost.

    Thanks, Tobias

  3. Oliver Grant plans the night

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

    Last night before the memo, so I'm closing out the three loose threads that actually change what I tell Marco and Tobias, and skipping anything merely confirmatory:

    1. The orphan subscription-delivery report came back strange: 0% of orphan customers were classified as "lapsed within 30 days" and 0% as "no subscription record at all" — yet 25-46% of orders are orphan. That means essentially all orphan customers have a subscription record, just not one whose status/date my query treated as active-and-overlapping. The likely candidates are 'paused' or 'incomplete' subscriptions, or cancellations that happened well before the 30-day window I checked. I need the actual status distribution before I can tell Tobias whether this is "paused customers still getting free boxes" (a real control gap) or something more benign.
    2. The corrected (pre-discount subtotal) lift report is strikingly consistent — every one of the 50 worst rows shows negative lift, and the pattern looks structural, not noise. But it's fragmented into 219 rows at the per-tenant-instance grain, which is too granular for the memo's headline number. I want one clean, order-weighted summary per promotion family (Welcome10 / Black Friday / January Sale / Summer Sale) so Marco and Tobias get a single defensible "no incremental lift, if anything smaller baskets" figure rather than a page of tenant fragments.
    3. The returns/refunds report surfaced two outsized ratios — a Welcome10 instance refunding 189% of its own discount cost, and a Volume-tier-10+ instance refunding 162% of its discount cost. Before stating "this discount is actively loss-making after refunds" in the memo, I want to check whether that's driven by a handful of large refunds (an outlier/concentration story, possibly one big account) versus broad-based returns across many orders (a genuine pattern worth capping the discount over).

    These three reports close out Marco's Q3/Q4 and Tobias's Q1/Q2 with concrete, checked numbers for Friday.

    Concentration of refund cost on the two highest refund-to-discount-ratio instances
    Question
    For the two discount instances whose total refunds exceeded their own discount cost (Welcome 10% off with 260 orders, Volume tier 10+ with 104 orders, both from the prior return-rate report), is that refund cost driven by a handful of large refunds or spread broadly across many orders?
    One row per
    discount instance (2 rows)
    Columns
    • discount name
    • order count (used to confirm identity: 260 for Welcome 10% off, 104 for Volume tier 10+)
    • total refunded amount, status='refunded' (EUR)
    • refund count (number of refunded order_returns)
    • top 3 single refunds as % of total refunded amount
    • median single refund amount (EUR)
    • max single refund amount (EUR)
    • % of this discount's orders that were refunded in full (refund_total >= order grand_total)
  4. Omar 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 discount_orders AS (
      SELECT od.discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total, o.currency_code
      FROM order_discounts od
      JOIN discounts d ON d.id = od.discount_id
      JOIN orders o ON o.id = od.order_id
      WHERE d.name IN ('Welcome 10% off', 'Volume tier 10+')
        AND o.status <> 'cancelled'
        AND o.placed_at >= DATE '2025-01-01'
        AND o.placed_at < DATE '2026-01-01'
    ),
    discount_counts AS (
      SELECT discount_id, discount_name, COUNT(*) AS order_count
      FROM discount_orders
      GROUP BY discount_id, discount_name
    ),
    target_discounts AS (
      SELECT discount_id, discount_name, order_count
      FROM discount_counts
      WHERE (discount_name = 'Welcome 10% off' AND order_count = 260)
         OR (discount_name = 'Volume tier 10+' AND order_count = 104)
    ),
    target_orders AS (
      SELECT do2.discount_id, td.discount_name, td.order_count, do2.order_id, do2.grand_total, do2.currency_code
      FROM discount_orders do2
      JOIN target_discounts td ON td.discount_id = do2.discount_id
    ),
    refunds AS (
      SELECT
        tord.discount_id,
        tord.discount_name,
        tord.order_count,
        tord.order_id,
        tord.grand_total,
        orr.id AS return_id,
        orr.refund_total,
        orr.refunded_at,
        (orr.refund_total / er.rate) AS refund_eur
      FROM target_orders tord
      JOIN order_returns orr ON orr.order_id = tord.order_id AND orr.status = 'refunded'
      JOIN exchange_rates er ON er.base_code = 'EUR'
        AND er.quote_code = orr.currency_code
        AND er.as_of = CAST(orr.refunded_at AS date)
    ),
    order_refund_totals AS (
      SELECT discount_id, discount_name, order_id, grand_total, SUM(refund_total) AS total_refund_native
      FROM refunds
      GROUP BY discount_id, discount_name, order_id, grand_total
    ),
    ranked_refunds AS (
      SELECT
        discount_id,
        discount_name,
        refund_eur,
        ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC) AS rn
      FROM refunds
    ),
    discount_agg AS (
      SELECT
        discount_id,
        discount_name,
        COUNT(*) AS refund_count,
        SUM(refund_eur) AS total_refund_eur,
        MAX(refund_eur) AS max_refund_eur,
        PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY refund_eur) AS median_refund_eur
      FROM refunds
      GROUP BY discount_id, discount_name
    ),
    top3_agg AS (
      SELECT discount_id, SUM(refund_eur) AS top3_sum
      FROM ranked_refunds
      WHERE rn <= 3
      GROUP BY discount_id
    ),
    full_refund_agg AS (
      SELECT discount_id, COUNT(*) AS full_refund_orders
      FROM order_refund_totals
      WHERE total_refund_native >= grand_total
      GROUP BY discount_id
    )
    SELECT
      td.discount_name AS discount_name,
      td.order_count AS order_count,
      ROUND(da.total_refund_eur, 2) AS total_refunded_eur,
      da.refund_count AS refund_count,
      ROUND(100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0), 1) AS top3_pct_of_total,
      ROUND(da.median_refund_eur, 2) AS median_refund_eur,
      ROUND(da.max_refund_eur, 2) AS max_refund_eur,
      ROUND(100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count, 1) AS pct_orders_fully_refunded
    FROM target_discounts td
    JOIN discount_agg da ON da.discount_id = td.discount_id
    LEFT JOIN top3_agg t3 ON t3.discount_id = td.discount_id
    LEFT JOIN full_refund_agg fr ON fr.discount_id = td.discount_id
    ORDER BY td.discount_name ASC

    “Query compiles cleanly and returns exactly the requested columns at the discount-instance grain. 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 approach: - Re-derived the two discount instances by matching discount name + exact 2025 non-cancelled order count (260 for "Welcome 10% off", 104 for "Volume tier 10+") via order_discounts → orders. - Pulled order_returns with status='refunded' for those orders, converting each refund to EUR using exchange_rates (EUR base, refund's currency as quote, rate as of the refund date). - Computed total refunded, refund count, top-3-refunds share of total, median and max refund (all in EUR), and the share of that discount's orders that were fully refunded (summed native-currency refunds per order ≥ order grand_total, to handle multi-refund orders correctly). - One row per discount, ordered by name, 8 columns — within the grain/width/length limits.”

  5. The report comes back overnight

    As Oliver Grant saw it, from the small dataset the agents worked on

    discount_name   | order_count | total_refunded_eur | refund_count | top3_pct_of_total | median_refund_eur | max_refund_eur | pct_orders_fully_refunded
    ----------------+-------------+--------------------+--------------+-------------------+-------------------+----------------+--------------------------
    Volume tier 10+ |         104 |           18050.36 |            8 |              93.9 |            415.17 |        9230.66 |                       1.9
    Welcome 10% off |         260 |           12243.62 |           92 |              17.7 |             77.47 |         988.21 |                       4.6
    (2 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 q159

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

    • determinismtie-breaker: target_discounts is keyed by discount_id
    • numericsdocs/NUMERICS.md: rounding removed; results keep full precision
    • 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 (16×)
    • placeholderpercentile cont
    • determinismthe standard leaves the place of NULLs in a sort to the implementation: NULLS LAST ascending, NULLS FIRST descending, as in the reference results (3×)
    The benchmark text, against the submitted SQL
    WITH discount_orders AS (  SELECT od.discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total, o.currency_code  SELECT od.discount_id AS discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total AS grand_total, o.currency_code AS currency_code  FROM order_discounts od  JOIN discounts d ON d.id = od.discount_id  JOIN orders o ON o.id = od.order_id  WHERE d.name IN ('Welcome 10% off', 'Volume tier 10+')    AND o.status <> 'cancelled'    AND o.placed_at >= DATE '2025-01-01'    AND o.placed_at < DATE '2026-01-01'),discount_counts AS (  SELECT discount_id, discount_name, COUNT(*) AS order_count  FROM discount_orders  GROUP BY discount_id, discount_name),target_discounts AS (  SELECT discount_id, discount_name, order_count  FROM discount_counts  WHERE (discount_name = 'Welcome 10% off' AND order_count = 260)     OR (discount_name = 'Volume tier 10+' AND order_count = 104)),target_orders AS (  SELECT do2.discount_id, td.discount_name, td.order_count, do2.order_id, do2.grand_total, do2.currency_code  SELECT do2.discount_id AS discount_id, td.discount_name AS discount_name, td.order_count AS order_count, do2.order_id AS order_id, do2.grand_total AS grand_total, do2.currency_code AS currency_code  FROM discount_orders do2  JOIN target_discounts td ON td.discount_id = do2.discount_id),refunds AS (  SELECT    tord.discount_id,    tord.discount_name,    tord.order_count,    tord.order_id,    tord.grand_total,    tord.discount_id AS discount_id,    tord.discount_name AS discount_name,    tord.order_count AS order_count,    tord.order_id AS order_id,    tord.grand_total AS grand_total,    orr.id AS return_id,    orr.refund_total,    orr.refunded_at,    (orr.refund_total / er.rate) AS refund_eur    orr.refund_total AS refund_total,    orr.refunded_at AS refunded_at,    (CAST(orr.refund_total / er.rate AS NUMERIC(18,6))) AS refund_eur  FROM target_orders tord  JOIN order_returns orr ON orr.order_id = tord.order_id AND orr.status = 'refunded'  JOIN exchange_rates er ON er.base_code = 'EUR'    AND er.quote_code = orr.currency_code    AND er.as_of = CAST(orr.refunded_at AS date)),order_refund_totals AS (  SELECT discount_id, discount_name, order_id, grand_total, SUM(refund_total) AS total_refund_native  FROM refunds  GROUP BY discount_id, discount_name, order_id, grand_total),ranked_refunds AS (  SELECT    discount_id,    discount_name,    refund_eur,    ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC) AS rn    ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC NULLS FIRST) AS rn  FROM refunds),discount_agg AS (  SELECT    discount_id,    discount_name,    COUNT(*) AS refund_count,    SUM(refund_eur) AS total_refund_eur,    MAX(refund_eur) AS max_refund_eur,    PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY refund_eur) AS median_refund_eur    {{percentile_cont(0.5, refund_eur)}} AS median_refund_eur  FROM refunds  GROUP BY discount_id, discount_name),top3_agg AS (  SELECT discount_id, SUM(refund_eur) AS top3_sum  FROM ranked_refunds  WHERE rn <= 3  GROUP BY discount_id),full_refund_agg AS (  SELECT discount_id, COUNT(*) AS full_refund_orders  FROM order_refund_totals  WHERE total_refund_native >= grand_total  GROUP BY discount_id)SELECT  td.discount_name AS discount_name,  td.order_count AS order_count,  ROUND(da.total_refund_eur, 2) AS total_refunded_eur,  da.total_refund_eur AS total_refunded_eur,  da.refund_count AS refund_count,  ROUND(100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0), 1) AS top3_pct_of_total,  ROUND(da.median_refund_eur, 2) AS median_refund_eur,  ROUND(da.max_refund_eur, 2) AS max_refund_eur,  ROUND(100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count, 1) AS pct_orders_fully_refunded  100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0) AS top3_pct_of_total,  da.median_refund_eur AS median_refund_eur,  da.max_refund_eur AS max_refund_eur,  100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count AS pct_orders_fully_refundedFROM target_discounts tdJOIN discount_agg da ON da.discount_id = td.discount_idLEFT JOIN top3_agg t3 ON t3.discount_id = td.discount_idLEFT JOIN full_refund_agg fr ON fr.discount_id = td.discount_idORDER BY td.discount_name ASCORDER BY td.discount_name ASC NULLS LAST, td.discount_id NULLS LAST
    WITH discount_orders AS (
      SELECT od.discount_id AS discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total AS grand_total, o.currency_code AS currency_code
      FROM order_discounts od
      JOIN discounts d ON d.id = od.discount_id
      JOIN orders o ON o.id = od.order_id
      WHERE d.name IN ('Welcome 10% off', 'Volume tier 10+')
        AND o.status <> 'cancelled'
        AND o.placed_at >= DATE '2025-01-01'
        AND o.placed_at < DATE '2026-01-01'
    ),
    discount_counts AS (
      SELECT discount_id, discount_name, COUNT(*) AS order_count
      FROM discount_orders
      GROUP BY discount_id, discount_name
    ),
    target_discounts AS (
      SELECT discount_id, discount_name, order_count
      FROM discount_counts
      WHERE (discount_name = 'Welcome 10% off' AND order_count = 260)
         OR (discount_name = 'Volume tier 10+' AND order_count = 104)
    ),
    target_orders AS (
      SELECT do2.discount_id AS discount_id, td.discount_name AS discount_name, td.order_count AS order_count, do2.order_id AS order_id, do2.grand_total AS grand_total, do2.currency_code AS currency_code
      FROM discount_orders do2
      JOIN target_discounts td ON td.discount_id = do2.discount_id
    ),
    refunds AS (
      SELECT
        tord.discount_id AS discount_id,
        tord.discount_name AS discount_name,
        tord.order_count AS order_count,
        tord.order_id AS order_id,
        tord.grand_total AS grand_total,
        orr.id AS return_id,
        orr.refund_total AS refund_total,
        orr.refunded_at AS refunded_at,
        (CAST(orr.refund_total / er.rate AS NUMERIC(18,6))) AS refund_eur
      FROM target_orders tord
      JOIN order_returns orr ON orr.order_id = tord.order_id AND orr.status = 'refunded'
      JOIN exchange_rates er ON er.base_code = 'EUR'
        AND er.quote_code = orr.currency_code
        AND er.as_of = CAST(orr.refunded_at AS date)
    ),
    order_refund_totals AS (
      SELECT discount_id, discount_name, order_id, grand_total, SUM(refund_total) AS total_refund_native
      FROM refunds
      GROUP BY discount_id, discount_name, order_id, grand_total
    ),
    ranked_refunds AS (
      SELECT
        discount_id,
        discount_name,
        refund_eur,
        ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC NULLS FIRST) AS rn
      FROM refunds
    ),
    discount_agg AS (
      SELECT
        discount_id,
        discount_name,
        COUNT(*) AS refund_count,
        SUM(refund_eur) AS total_refund_eur,
        MAX(refund_eur) AS max_refund_eur,
        PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY refund_eur) AS median_refund_eur
      FROM refunds
      GROUP BY discount_id, discount_name
    ),
    top3_agg AS (
      SELECT discount_id, SUM(refund_eur) AS top3_sum
      FROM ranked_refunds
      WHERE rn <= 3
      GROUP BY discount_id
    ),
    full_refund_agg AS (
      SELECT discount_id, COUNT(*) AS full_refund_orders
      FROM order_refund_totals
      WHERE total_refund_native >= grand_total
      GROUP BY discount_id
    )
    SELECT
      td.discount_name AS discount_name,
      td.order_count AS order_count,
      da.total_refund_eur AS total_refunded_eur,
      da.refund_count AS refund_count,
      100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0) AS top3_pct_of_total,
      da.median_refund_eur AS median_refund_eur,
      da.max_refund_eur AS max_refund_eur,
      100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count AS pct_orders_fully_refunded
    FROM target_discounts td
    JOIN discount_agg da ON da.discount_id = td.discount_id
    LEFT JOIN top3_agg t3 ON t3.discount_id = td.discount_id
    LEFT JOIN full_refund_agg fr ON fr.discount_id = td.discount_id
    ORDER BY td.discount_name ASC NULLS LAST, td.discount_id NULLS LAST
    10 ms100 ms1 s10 sHyper55.9 msDuckDB110 msGizmoSQL104 msclickhouse_brew474 msFirebolterrorDataFusion1.55 sClickHouseerror
    • Firebolt{ "errors": [ { "description": "Line 37, Column 28: 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": "9d99048f-4bde-49e7-a1b8-be7491903c02", "query_lab
    • ClickHouseCode: 69. DB::Exception: Decimal result's scale is less than argument's one: while executing function divide on arguments __table20.refund_total Decimal(14, 4) Decimal64(size = 0), __table21.rate Decimal(12, 6) Decimal64(size = 0). (ARGUMENT_OUT_OF_BOUND)
  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

    Omar's whole session, 7 turns
    • The request, as Omar received it
      Report request from Oliver Grant (analyst for the Head of Pricing and Promotions):
      
      Title: Concentration of refund cost on the two highest refund-to-discount-ratio instances
      Question: For the two discount instances whose total refunds exceeded their own discount cost (Welcome 10% off with 260 orders, Volume tier 10+ with 104 orders, both from the prior return-rate report), is that refund cost driven by a handful of large refunds or spread broadly across many orders?
      Grain: one row per discount instance (2 rows)
      Columns:
      - discount name
      - order count (used to confirm identity: 260 for Welcome 10% off, 104 for Volume tier 10+)
      - total refunded amount, status='refunded' (EUR)
      - refund count (number of refunded order_returns)
      - top 3 single refunds as % of total refunded amount
      - median single refund amount (EUR)
      - max single refund amount (EUR)
      - % of this discount's orders that were refunded in full (refund_total >= order grand_total)
      Details: Source: identify the two discount_id instances exactly as in the prior return-rate report — discounts.name='Welcome 10% off' whose set of 2025 non-cancelled orders (via order_discounts) numbers exactly 260, and discounts.name='Volume tier 10+' whose matching order set numbers exactly 104. For those two discount_ids, pull order_returns (status='refunded') joined to orders (grand_total, currency_code) for the orders carrying that discount, convert refund_total to EUR via exchange_rates (base_code='EUR', quote_code=currency_code, as_of=refunded_at date). Compute total, count, median, max, top-3-as-%-of-total, and % of orders fully refunded. Order by discount name ascending. Print both rows.
      
      Check your query with the warehouse's dry_run tool, then hand it in with submit.
    • Omar calls dry_run
      WITH discount_orders AS (
        SELECT od.discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total, o.currency_code
        FROM order_discounts od
        JOIN discounts d ON d.id = od.discount_id
        JOIN orders o ON o.id = od.order_id
        WHERE d.name IN ('Welcome 10% off', 'Volume tier 10+')
          AND o.status <> 'cancelled'
          AND o.placed_at >= DATE '2025-01-01'
          AND o.placed_at < DATE '2026-01-01'
      ),
      discount_counts AS (
        SELECT discount_id, discount_name, COUNT(*) AS order_count
        FROM discount_orders
        GROUP BY discount_id, discount_name
      ),
      target_discounts AS (
        SELECT discount_id, discount_name, order_count
        FROM discount_counts
        WHERE (discount_name = 'Welcome 10% off' AND order_count = 260)
           OR (discount_name = 'Volume tier 10+' AND order_count = 104)
      ),
      target_orders AS (
        SELECT do2.discount_id, td.discount_name, td.order_count, do2.order_id, do2.grand_total, do2.currency_code
        FROM discount_orders do2
        JOIN target_discounts td ON td.discount_id = do2.discount_id
      ),
      refunds AS (
        SELECT
          tord.discount_id,
          tord.discount_name,
          tord.order_count,
          tord.order_id,
          tord.grand_total,
          orr.id AS return_id,
          orr.refund_total,
          orr.refunded_at,
          (orr.refund_total / er.rate) AS refund_eur
        FROM target_orders tord
        JOIN order_returns orr ON orr.order_id = tord.order_id AND orr.status = 'refunded'
        JOIN exchange_rates er ON er.base_code = 'EUR'
          AND er.quote_code = orr.currency_code
          AND er.as_of = CAST(orr.refunded_at AS date)
      ),
      order_refund_totals AS (
        SELECT discount_id, discount_name, order_id, grand_total, SUM(refund_total) AS total_refund_native
        FROM refunds
        GROUP BY discount_id, discount_name, order_id, grand_total
      ),
      ranked_refunds AS (
        SELECT
          discount_id,
          discount_name,
          refund_eur,
          ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC) AS rn
        FROM refunds
      ),
      discount_agg AS (
        SELECT
          discount_id,
          discount_name,
          COUNT(*) AS refund_count,
          SUM(refund_eur) AS total_refund_eur,
          MAX(refund_eur) AS max_refund_eur,
          PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY refund_eur) AS median_refund_eur
        FROM refunds
        GROUP BY discount_id, discount_name
      ),
      top3_agg AS (
        SELECT discount_id, SUM(refund_eur) AS top3_sum
        FROM ranked_refunds
        WHERE rn <= 3
        GROUP BY discount_id
      ),
      full_refund_agg AS (
        SELECT discount_id, COUNT(*) AS full_refund_orders
        FROM order_refund_totals
        WHERE total_refund_native >= grand_total
        GROUP BY discount_id
      )
      SELECT
        td.discount_name AS discount_name,
        td.order_count AS order_count,
        ROUND(da.total_refund_eur, 2) AS total_refunded_eur,
        da.refund_count AS refund_count,
        ROUND(100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0), 1) AS top3_pct_of_total,
        ROUND(da.median_refund_eur, 2) AS median_refund_eur,
        ROUND(da.max_refund_eur, 2) AS max_refund_eur,
        ROUND(100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count, 1) AS pct_orders_fully_refunded
      FROM target_discounts td
      JOIN discount_agg da ON da.discount_id = td.discount_id
      LEFT JOIN top3_agg t3 ON t3.discount_id = td.discount_id
      LEFT JOIN full_refund_agg fr ON fr.discount_id = td.discount_id
      ORDER BY td.discount_name ASC
    • The warehouse answers
      STATUS: COMPILES (dry run on the empty schema, no data read)
      COLUMNS: discount_name, order_count, total_refunded_eur, refund_count, top3_pct_of_total, median_refund_eur, max_refund_eur, pct_orders_fully_refunded
    • OmarQuery compiles cleanly and returns exactly the requested columns at the discount-instance grain. Submitting.
    • Omar calls submit
      WITH discount_orders AS (
        SELECT od.discount_id, d.name AS discount_name, o.id AS order_id, o.grand_total, o.currency_code
        FROM order_discounts od
        JOIN discounts d ON d.id = od.discount_id
        JOIN orders o ON o.id = od.order_id
        WHERE d.name IN ('Welcome 10% off', 'Volume tier 10+')
          AND o.status <> 'cancelled'
          AND o.placed_at >= DATE '2025-01-01'
          AND o.placed_at < DATE '2026-01-01'
      ),
      discount_counts AS (
        SELECT discount_id, discount_name, COUNT(*) AS order_count
        FROM discount_orders
        GROUP BY discount_id, discount_name
      ),
      target_discounts AS (
        SELECT discount_id, discount_name, order_count
        FROM discount_counts
        WHERE (discount_name = 'Welcome 10% off' AND order_count = 260)
           OR (discount_name = 'Volume tier 10+' AND order_count = 104)
      ),
      target_orders AS (
        SELECT do2.discount_id, td.discount_name, td.order_count, do2.order_id, do2.grand_total, do2.currency_code
        FROM discount_orders do2
        JOIN target_discounts td ON td.discount_id = do2.discount_id
      ),
      refunds AS (
        SELECT
          tord.discount_id,
          tord.discount_name,
          tord.order_count,
          tord.order_id,
          tord.grand_total,
          orr.id AS return_id,
          orr.refund_total,
          orr.refunded_at,
          (orr.refund_total / er.rate) AS refund_eur
        FROM target_orders tord
        JOIN order_returns orr ON orr.order_id = tord.order_id AND orr.status = 'refunded'
        JOIN exchange_rates er ON er.base_code = 'EUR'
          AND er.quote_code = orr.currency_code
          AND er.as_of = CAST(orr.refunded_at AS date)
      ),
      order_refund_totals AS (
        SELECT discount_id, discount_name, order_id, grand_total, SUM(refund_total) AS total_refund_native
        FROM refunds
        GROUP BY discount_id, discount_name, order_id, grand_total
      ),
      ranked_refunds AS (
        SELECT
          discount_id,
          discount_name,
          refund_eur,
          ROW_NUMBER() OVER (PARTITION BY discount_id ORDER BY refund_eur DESC) AS rn
        FROM refunds
      ),
      discount_agg AS (
        SELECT
          discount_id,
          discount_name,
          COUNT(*) AS refund_count,
          SUM(refund_eur) AS total_refund_eur,
          MAX(refund_eur) AS max_refund_eur,
          PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY refund_eur) AS median_refund_eur
        FROM refunds
        GROUP BY discount_id, discount_name
      ),
      top3_agg AS (
        SELECT discount_id, SUM(refund_eur) AS top3_sum
        FROM ranked_refunds
        WHERE rn <= 3
        GROUP BY discount_id
      ),
      full_refund_agg AS (
        SELECT discount_id, COUNT(*) AS full_refund_orders
        FROM order_refund_totals
        WHERE total_refund_native >= grand_total
        GROUP BY discount_id
      )
      SELECT
        td.discount_name AS discount_name,
        td.order_count AS order_count,
        ROUND(da.total_refund_eur, 2) AS total_refunded_eur,
        da.refund_count AS refund_count,
        ROUND(100.0 * t3.top3_sum / NULLIF(da.total_refund_eur,0), 1) AS top3_pct_of_total,
        ROUND(da.median_refund_eur, 2) AS median_refund_eur,
        ROUND(da.max_refund_eur, 2) AS max_refund_eur,
        ROUND(100.0 * COALESCE(fr.full_refund_orders,0) / td.order_count, 1) AS pct_orders_fully_refunded
      FROM target_discounts td
      JOIN discount_agg da ON da.discount_id = td.discount_id
      LEFT JOIN top3_agg t3 ON t3.discount_id = td.discount_id
      LEFT JOIN full_refund_agg fr ON fr.discount_id = td.discount_id
      ORDER BY td.discount_name ASC
    • The warehouse answers
      Submitted to tonight's batch. Your work on this request is done.
    • OmarSubmitted. Summary of approach: - Re-derived the two discount instances by matching discount name + exact 2025 non-cancelled order count (260 for "Welcome 10% off", 104 for "Volume tier 10+") via `order_discounts` → `orders`. - Pulled `order_returns` with `status='refunded'` for those orders, converting each refund to EUR using `exchange_rates` (EUR base, refund's currency as quote, rate as of the refund date). - Computed total refunded, refund count, top-3-refunds share of total, median and max refund (all in EUR), and the share of that discount's orders that were fully refunded (summed native-currency refunds per order ≥ order grand_total, to handle multi-refund orders correctly). - One row per discount, ordered by name, 8 columns — within the grain/width/length limits.