-- Each plan row is one month x region x product. Money is integer USD cents.
-- The actual order table has one row per order line. Credits are assigned to
-- the original sale period for this management-reporting example (not GAAP).
-- Aggregate actuals BEFORE joining to plan; otherwise targets would be multiplied.
CREATE OR REPLACE TEMP VIEW actual_by_cell AS
SELECT
  strftime(CAST(order_date AS DATE), '%Y-%m') AS month,
  region, product,
  SUM(units)::BIGINT AS actual_units,
  SUM(units * gross_unit_price_cents)::BIGINT AS gross_cents,
  SUM(discount_cents)::BIGINT AS discount_cents,
  SUM(refund_cents)::BIGINT AS refund_cents,
  SUM(units * gross_unit_price_cents - discount_cents - refund_cents)::BIGINT AS actual_net_cents
FROM actual_orders
GROUP BY 1,2,3;

CREATE OR REPLACE TEMP VIEW bridge AS
SELECT
  p.month, p.region, p.product,
  p.planned_units,
  p.planned_net_unit_price_cents,
  COALESCE(a.actual_units,0) AS actual_units,
  COALESCE(a.gross_cents,0) AS gross_cents,
  COALESCE(a.discount_cents,0) AS discount_cents,
  COALESCE(a.refund_cents,0) AS refund_cents,
  p.planned_units*p.planned_net_unit_price_cents AS plan_net_cents,
  COALESCE(a.actual_net_cents,0) AS actual_net_cents,
  COALESCE(a.actual_net_cents,0)-p.planned_units*p.planned_net_unit_price_cents AS variance_cents,
  (COALESCE(a.actual_units,0)-p.planned_units)*p.planned_net_unit_price_cents AS volume_mix_effect_cents,
  COALESCE(a.actual_net_cents,0)-COALESCE(a.actual_units,0)*p.planned_net_unit_price_cents AS net_price_effect_cents
FROM plan p LEFT JOIN actual_by_cell a USING(month,region,product);
-- Bridge identity for each cell and every rollup:
-- actual - plan = (actual units - planned units) * planned net price
--               + (actual net revenue - actual units * planned net price).
-- Volume/mix combines quantity changes at cell-level plan prices. It is not
-- a separate causal estimate of mix; net-price includes discounts and refunds.
