rheaarchived
- 40 commits
- 1 branch
- 0 tags
- updated
analysis_queries.sql
12.2 KB · 342 lines
1-- ============================================================2-- Rhea analytical queries3-- Each query stands alone — paste into Metabase (native question)4-- or Jupyter. All build on v_prices / base tables; line_type5-- filtering is already handled by the views.6-- ============================================================78-- ------------------------------------------------------------9-- 1. TOTAL SPEND10-- ------------------------------------------------------------1112-- 1a. All-time grocery spend13SELECT SUM(total) AS total_spend, COUNT(*) AS n_receipts14FROM receipts;1516-- 1b. Spend per month (Metabase line chart)17SELECT date_trunc('month', purchase_date)::date AS month,18 SUM(total) AS spend,19 COUNT(*) AS trips20FROM receipts21GROUP BY 1 ORDER BY 1;2223-- 1c. Spend by month AND chain (stacked bar)24SELECT date_trunc('month', purchase_date)::date AS month,25 chain,26 SUM(total) AS spend27FROM receipts28GROUP BY 1, 2 ORDER BY 1, 2;2930-- 1d. Spend by category (uses normalized product category)31SELECT COALESCE(product_category, 'unmapped') AS category,32 SUM(price_paid) AS spend,33 COUNT(*) AS n_purchases34FROM v_prices35GROUP BY 1 ORDER BY spend DESC;3637-- ------------------------------------------------------------38-- 2. RETAILER BREAKDOWN39-- ------------------------------------------------------------4041-- 2a. Which retailer gets our money42SELECT chain,43 SUM(total) AS spend,44 COUNT(*) AS trips,45 ROUND(AVG(total), 2) AS avg_basket,46 MIN(purchase_date) AS first_trip,47 MAX(purchase_date) AS last_trip48FROM receipts49GROUP BY chain ORDER BY spend DESC;5051-- 2b. Share of wallet over time (100% stacked area in Metabase)52SELECT date_trunc('month', purchase_date)::date AS month,53 chain,54 SUM(total) AS spend55FROM receipts56GROUP BY 1, 2 ORDER BY 1;5758-- ------------------------------------------------------------59-- 3. WHAT WE BUY MOST60-- ------------------------------------------------------------6162-- 3a. Most frequently purchased products63SELECT product,64 COUNT(*) AS times_bought,65 SUM(price_paid) AS total_spent,66 COUNT(DISTINCT chain) AS chains_bought_at67FROM v_prices68GROUP BY product69ORDER BY times_bought DESC70LIMIT 30;7172-- 3b. Where the money actually goes (by product)73SELECT product,74 SUM(price_paid) AS total_spent,75 COUNT(*) AS times_bought76FROM v_prices77GROUP BY product78ORDER BY total_spent DESC79LIMIT 30;8081-- 3c. Pounds purchased of by-weight staples82SELECT product,83 ROUND(SUM(weight_lbs), 1) AS total_lbs,84 ROUND(SUM(price_paid), 2) AS total_spent,85 ROUND(SUM(price_paid) / NULLIF(SUM(weight_lbs), 0), 2) AS blended_price_per_lb86FROM v_prices87WHERE effective_unit = 'lb'88GROUP BY product89ORDER BY total_lbs DESC90LIMIT 20;9192-- ------------------------------------------------------------93-- 4. CROSS-RETAILER PRICE COMPARISON (the point of all this)94-- ------------------------------------------------------------9596-- 4a. Head-to-head: products bought at 2+ chains, cheapest vs priciest chain97WITH per_chain AS (98 SELECT product, effective_unit, chain,99 AVG(effective_unit_price) AS avg_price,100 COUNT(*) AS n101 FROM v_prices102 WHERE effective_unit_price IS NOT NULL103 GROUP BY 1, 2, 3104),105spread AS (106 SELECT product, effective_unit,107 COUNT(*) AS n_chains,108 MIN(avg_price) AS cheapest,109 MAX(avg_price) AS priciest110 FROM per_chain111 GROUP BY 1, 2112 HAVING COUNT(*) >= 2113)114SELECT s.product,115 s.effective_unit,116 cheap.chain AS cheapest_at,117 ROUND(s.cheapest, 2) AS cheapest_price,118 exp.chain AS priciest_at,119 ROUND(s.priciest, 2) AS priciest_price,120 ROUND(100.0 * (s.priciest - s.cheapest) / s.cheapest, 0) AS pct_premium121FROM spread s122JOIN per_chain cheap ON cheap.product = s.product AND cheap.effective_unit = s.effective_unit123 AND cheap.avg_price = s.cheapest124JOIN per_chain exp ON exp.product = s.product AND exp.effective_unit = s.effective_unit125 AND exp.avg_price = s.priciest126ORDER BY pct_premium DESC;127128-- 4b. Single product deep-dive (swap the product name; Metabase: make it a filter variable)129SELECT chain, purchase_date, raw_name,130 effective_unit, effective_unit_price,131 weight_lbs, quantity, price_paid, on_sale132FROM v_prices133WHERE product = 'bananas' -- or: product LIKE '%yogurt%'134ORDER BY purchase_date;135136-- 4c. Which chain "wins" the most products (is cheapest most often)137WITH per_chain AS (138 SELECT product, chain, AVG(effective_unit_price) AS avg_price139 FROM v_prices140 WHERE effective_unit_price IS NOT NULL141 GROUP BY 1, 2142),143ranked AS (144 SELECT product, chain,145 RANK() OVER (PARTITION BY product ORDER BY avg_price) AS rnk,146 COUNT(*) OVER (PARTITION BY product) AS n_chains147 FROM per_chain148)149SELECT chain,150 COUNT(*) AS products_cheapest_at151FROM ranked152WHERE rnk = 1 AND n_chains >= 2153GROUP BY chain154ORDER BY products_cheapest_at DESC;155156-- 4d. The organic premium: same product organic vs not, per lb157WITH base AS (158 SELECT REPLACE(product, 'organic ', '') AS base_product,159 is_organic,160 AVG(effective_unit_price) AS avg_price161 FROM v_prices162 WHERE effective_unit = 'lb' AND effective_unit_price IS NOT NULL163 GROUP BY 1, 2164)165SELECT o.base_product,166 ROUND(c.avg_price, 2) AS conventional_per_lb,167 ROUND(o.avg_price, 2) AS organic_per_lb,168 ROUND(100.0 * (o.avg_price - c.avg_price) / c.avg_price, 0) AS organic_premium_pct169FROM base o170JOIN base c ON c.base_product = o.base_product171 AND o.is_organic IS TRUE AND c.is_organic IS FALSE172ORDER BY organic_premium_pct DESC;173174-- ------------------------------------------------------------175-- 5. SHOPPING FREQUENCY & HABITS176-- ------------------------------------------------------------177178-- 5a. How often we shop (trips per week, overall and by chain)179SELECT chain,180 COUNT(*) AS trips,181 ROUND(COUNT(*)::numeric /182 NULLIF((MAX(purchase_date) - MIN(purchase_date)) / 7.0, 0), 2) AS trips_per_week183FROM receipts184GROUP BY chain ORDER BY trips DESC;185186-- 5b. Days between trips (overall cadence)187WITH gaps AS (188 SELECT purchase_date - LAG(purchase_date) OVER (ORDER BY purchase_date) AS gap189 FROM receipts190)191SELECT ROUND(AVG(gap), 1) AS avg_days_between_trips,192 PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY gap) AS median_gap,193 MAX(gap) AS longest_gap194FROM gaps WHERE gap IS NOT NULL;195196-- 5c. Day-of-week habits197SELECT to_char(purchase_date, 'Dy') AS dow,198 COUNT(*) AS trips,199 ROUND(AVG(total), 2) AS avg_basket200FROM receipts201GROUP BY 1, EXTRACT(dow FROM purchase_date)202ORDER BY EXTRACT(dow FROM purchase_date);203204-- 5d. Repurchase cadence per product (how often do we rebuy bananas?)205WITH gaps AS (206 SELECT product,207 purchase_date - LAG(purchase_date) OVER (PARTITION BY product ORDER BY purchase_date) AS gap208 FROM v_prices209)210SELECT product,211 COUNT(*) + 1 AS times_bought,212 ROUND(AVG(gap), 1) AS avg_days_between213FROM gaps214WHERE gap IS NOT NULL215GROUP BY product216HAVING COUNT(*) >= 4217ORDER BY times_bought DESC218LIMIT 25;219220-- ------------------------------------------------------------221-- 6. SALES & DISCOUNTS222-- ------------------------------------------------------------223224-- 6a. Sale behavior per chain (are Safeway's sales real?)225SELECT * FROM v_chain_sale_stats ORDER BY pct_lines_on_sale DESC;226227-- 6b. Shelf price vs paid price per chain — "costs more but discounts more"?228SELECT chain,229 ROUND(AVG(effective_unit_list_price), 2) AS avg_shelf_unit_price,230 ROUND(AVG(effective_unit_price), 2) AS avg_paid_unit_price,231 ROUND(100.0 * (AVG(effective_unit_list_price) - AVG(effective_unit_price))232 / NULLIF(AVG(effective_unit_list_price), 0), 1) AS avg_realized_discount_pct233FROM v_prices234WHERE effective_unit_list_price IS NOT NULL235GROUP BY chain ORDER BY avg_shelf_unit_price DESC;236237-- 6c. Our best scores (biggest single-line discounts)238SELECT purchase_date, chain, product,239 list_price, price_paid, discount_amount, discount_pct240FROM v_prices241WHERE on_sale242ORDER BY discount_amount DESC243LIMIT 25;244245-- 6d. Total saved per month246SELECT date_trunc('month', purchase_date)::date AS month,247 SUM(discount_amount) AS saved,248 SUM(price_paid) AS spent249FROM v_prices250GROUP BY 1 ORDER BY 1;251252-- ------------------------------------------------------------253-- 7. PRICE TRENDS (personal inflation)254-- ------------------------------------------------------------255256-- 7a. Price history for one product across chains (line chart, one line per chain)257SELECT purchase_date, chain, effective_unit_price258FROM v_prices259WHERE product = 'bananas' AND effective_unit_price IS NOT NULL260ORDER BY purchase_date;261262-- 7b. Personal price index: avg unit price of repeat staples, by quarter263WITH staples AS (264 SELECT product FROM v_prices265 GROUP BY product HAVING COUNT(*) >= 6266)267SELECT date_trunc('quarter', purchase_date)::date AS quarter,268 ROUND(AVG(effective_unit_price), 2) AS avg_staple_unit_price269FROM v_prices270WHERE product IN (SELECT product FROM staples)271 AND effective_unit_price IS NOT NULL272GROUP BY 1 ORDER BY 1;273274-- 7c. Products whose price rose the most (first vs last purchase)275WITH firsts AS (276 SELECT DISTINCT ON (product) product,277 effective_unit_price AS first_price, purchase_date AS first_date278 FROM v_prices WHERE effective_unit_price IS NOT NULL279 ORDER BY product, purchase_date280),281lasts AS (282 SELECT DISTINCT ON (product) product,283 effective_unit_price AS last_price, purchase_date AS last_date284 FROM v_prices WHERE effective_unit_price IS NOT NULL285 ORDER BY product, purchase_date DESC286)287SELECT f.product, f.first_date, f.first_price, l.last_date, l.last_price,288 ROUND(100.0 * (l.last_price - f.first_price) / f.first_price, 0) AS pct_change289FROM firsts f290JOIN lasts l USING (product)291WHERE l.last_date > f.first_date + 60 -- at least ~2 months apart292 AND f.first_price > 0293ORDER BY pct_change DESC294LIMIT 25;295296-- ------------------------------------------------------------297-- 8. ODDS & ENDS298-- ------------------------------------------------------------299300-- 8a. Biggest single baskets301SELECT purchase_date, chain, total,302 (SELECT COUNT(*) FROM receipt_line_items li WHERE li.receipt_id = r.id) AS n_items303FROM receipts r304ORDER BY total DESC LIMIT 10;305306-- 8b. Deposits & fees paid over time (CRV, bag fees)307SELECT date_trunc('month', r.purchase_date)::date AS month,308 li.line_type,309 SUM(li.price_paid) AS amount310FROM receipt_line_items li JOIN receipts r ON r.id = li.receipt_id311WHERE li.line_type IN ('deposit', 'fee')312GROUP BY 1, 2 ORDER BY 1;313314-- 8c. Non-grocery spend hiding in grocery runs (Costco effect)315SELECT r.chain, li.raw_name, li.common_name, li.price_paid, r.purchase_date316FROM receipt_line_items li JOIN receipts r ON r.id = li.receipt_id317WHERE li.line_type = 'non_grocery'318ORDER BY li.price_paid DESC;319320-- 8d. Products we only ever buy at one chain (loyalty / availability)321SELECT product, MAX(chain) AS only_chain,322 COUNT(*) AS times_bought, SUM(price_paid) AS spent323FROM v_prices324GROUP BY product325HAVING COUNT(DISTINCT chain) = 1 AND COUNT(*) >= 5326ORDER BY spent DESC;327328-- 8e. Price volatility: staples with the widest price swings329SELECT product, effective_unit,330 COUNT(*) AS n,331 ROUND(MIN(effective_unit_price), 2) AS min_price,332 ROUND(MAX(effective_unit_price), 2) AS max_price,333 ROUND(STDDEV(effective_unit_price), 2) AS stddev334FROM v_prices335WHERE effective_unit_price IS NOT NULL336GROUP BY 1, 2337HAVING COUNT(*) >= 5338ORDER BY stddev DESC NULLS LAST339LIMIT 25;340341-- 8f. Data quality: receipts whose lines don't reconcile (should be only the 3 damaged scans)342SELECT * FROM v_receipt_qc WHERE ABS(COALESCE(unexplained_diff, 0)) > 0.02;