CREATE VIEW drh_agp_metrics AS
WITH glucose_data AS (
SELECT
gr.participant_id,
gr.Date_Time AS timestamp,
strftime('%Y-%m-%d %H', gr.Date_Time) AS hourValue,
gr.CGM_Value AS glucose_level
FROM
combined_cgm_tracing gr
),
ranked_data AS (
SELECT
participant_id,
hourValue,
glucose_level,
ROW_NUMBER() OVER (PARTITION BY participant_id, hourValue ORDER BY glucose_level) AS row_num,
COUNT(*) OVER (PARTITION BY participant_id, hourValue) AS total_count
FROM
glucose_data
),
percentiles AS (
SELECT
participant_id,
hourValue AS hour,
MAX(CASE WHEN row_num = CAST(0.05 * total_count AS INT) THEN glucose_level END) AS p5,
MAX(CASE WHEN row_num = CAST(0.25 * total_count AS INT) THEN glucose_level END) AS p25,
MAX(CASE WHEN row_num = CAST(0.50 * total_count AS INT) THEN glucose_level END) AS p50,
MAX(CASE WHEN row_num = CAST(0.75 * total_count AS INT) THEN glucose_level END) AS p75,
MAX(CASE WHEN row_num = CAST(0.95 * total_count AS INT) THEN glucose_level END) AS p95
FROM
ranked_data
GROUP BY
participant_id, hour
),
hourly_averages AS (
SELECT
participant_id,
SUBSTR(hour, 1, 10) AS date,
SUBSTR(hour, 12) AS hour,
COALESCE(AVG(p5), 0) AS p5,
COALESCE(AVG(p25), 0) AS p25,
COALESCE(AVG(p50), 0) AS p50,
COALESCE(AVG(p75), 0) AS p75,
COALESCE(AVG(p95), 0) AS p95
FROM
percentiles
GROUP BY
participant_id, hour
)
SELECT
participant_id,
hour,
COALESCE(AVG(p5), 0) AS p5,
COALESCE(AVG(p25), 0) AS p25,
COALESCE(AVG(p50), 0) AS p50,
COALESCE(AVG(p75), 0) AS p75,
COALESCE(AVG(p95), 0) AS p95
FROM
hourly_averages
GROUP BY
participant_id, hour
ORDER BY
participant_id, hour