 WITH gtime AS (
  SELECT MAX("time") AS time FROM "glucose-processed-full" LIMIT 1
),
stime AS (
SELECT MIN("glucose-processed"."time") AS time FROM "glucose-processed" LIMIT 1
),
 avgs AS (
         SELECT "glucose-processed"."time",
            "glucose-processed".smoothval,
            "glucose-processed".absvalue,
            "glucose-processed".delta1st,
            "glucose-processed".delta2nd,
            ema("glucose-processed".delta1st, 0.25::real) OVER (ORDER BY "glucose-processed"."time") AS smoothdelta1st,
            ema("glucose-processed".delta2nd, 0.25::real) OVER (ORDER BY "glucose-processed"."time") AS smoothdelta2nd,
            stddev("glucose-processed".delta1st) OVER (ORDER BY "glucose-processed"."time" RANGE BETWEEN '02:00:00'::interval PRECEDING AND CURRENT ROW) AS std_dev_delta1st,
            avg("glucose-processed".absvalue) OVER (ORDER BY "glucose-processed"."time" RANGE BETWEEN '3 mons'::interval PRECEDING AND CURRENT ROW) AS "3mo_eabg",
            avg("glucose-processed".absvalue) OVER (ORDER BY "glucose-processed"."time" RANGE BETWEEN '7 days'::interval PRECEDING AND CURRENT ROW) AS "7day_eabg"
           FROM "glucose-processed"
		   LEFT JOIN "stime" ON 1=1
		   LEFT JOIN "gtime" ON 1=1
		   WHERE "glucose-processed"."time" >= COALESCE(gtime.time, stime.time)
          ORDER BY "glucose-processed"."time"
        )
INSERT INTO "glucose-processed-full"
 SELECT "time",
    absvalue,
    delta1st,
    delta2nd,
	smoothval,
    std_dev_delta1st,
    "3mo_eabg",
    "7day_eabg",
    ("3mo_eabg" + 46.7::double precision) / 28.7::double precision AS "3mo_ea1c",
    ("7day_eabg" + 46.7::double precision) / 28.7::double precision AS "7day_ea1c",
	smoothdelta1st,
    smoothdelta2nd
   FROM avgs WHERE std_dev_delta1st IS NOT NULL
