Query editor
/*This query calculates a 2-year rolling median ETH price, anchored to thelast available data point of each month for the past 2 years.It also returns the specific price at that end-of-month anchor point.*/WITH monthly_ends AS (-- Step 1: Find the latest timestamp available in the data for each month.-- We look back further than 2 years (e.g., 4 years) to ensure that-- our first data point (from 2 years ago) has a full 2-year window-- of data *before* it to calculate its median.SELECTdate_trunc('month', minute) AS month_start,MAX(minute) AS end_of_month_timestampFROM prices.usdWHERE symbol = 'ETH'AND minute >= now() - INTERVAL '4' YEAR -- Look back far enough to build the first 2yr windowGROUP BY 1),end_of_month_prices AS (-- Step 2: Get the actual price at that latest timestamp for each month.-- We also filter here to only return the final results for the past 2 years.SELECTt1.month_start,t1.end_of_month_timestamp,t2.price AS price_at_eomFROM monthly_ends AS t1JOIN prices.usd AS t2ON t1.end_of_month_timestamp = t2.minuteAND t2.symbol = 'ETH'WHERE t1.end_of_month_timestamp >= now() - INTERVAL '2' YEAR)-- Step 3: For each end-of-month record, use a LATERAL join to-- calculate the median over the 2-year period *preceding* that record.SELECTeom.month_start,eom.end_of_month_timestamp,eom.price_at_eom,rolling_median.median_eth_usd_2y,rolling_median.window_start,rolling_median.window_endFROM end_of_month_prices AS eomCROSS JOIN LATERAL (-- This subquery runs for *each* row from 'eom'SELECTapprox_percentile(price, 0.5) AS median_eth_usd_2y,MIN(minute) AS window_start,MAX(minute) AS window_endFROM prices.usdWHERE symbol = 'ETH'-- Define the 2-year rolling window:AND minute >= eom.end_of_month_timestamp - INTERVAL '2' YEARAND minute <= eom.end_of_month_timestamp) AS rolling_medianORDER BY eom.month_start DESC;