-- Snowflake version: Check dispensing by VTM (Virtual Therapeutic Moiety)
-- Uses GPMeds dispensing data from NATIONAL.GPMED

WITH SnomedCodes AS (
    SELECT "ProductSnomedCode", "ProductDescription"
    FROM DATA_HUB.DWH."DimMedicineAndDevice"
    WHERE "TherapeuticMoietySnomedCode" = '41145911000001106'  -- Tirzepatide VTM
),
LatestPeriod AS (
    SELECT MAX("ProcessingPeriodDate") AS MaxPeriodDate
    FROM NATIONAL.GPMED."MedicinesDispensedInPrimarycare"
)
SELECT *
FROM NATIONAL.GPMED."MedicinesDispensedInPrimarycare" gpm
INNER JOIN SnomedCodes sc ON gpm."PaiddmdCode" = sc."ProductSnomedCode"
CROSS JOIN LatestPeriod lp
WHERE gpm."ProcessingPeriodDate" > DATEADD(MONTH, -1, lp.MaxPeriodDate)
    AND gpm."ProcessingPeriodDate" <= lp.MaxPeriodDate
limit 100;


SELECT
    COUNT(DISTINCT gpm."PatientPseudonym") AS UniquePatientCount,
    MAX(gpm."ProcessingPeriodDate") AS LatestPeriod
FROM NATIONAL.GPMED."MedicinesDispensedInPrimarycare" gpm
INNER JOIN SnomedCodes sc ON gpm."PaiddmdCode" = sc."ProductSnomedCode"
CROSS JOIN LatestPeriod lp
WHERE gpm."ProcessingPeriodDate" > DATEADD(MONTH, -1, lp.MaxPeriodDate)
    AND gpm."ProcessingPeriodDate" <= lp.MaxPeriodDate;
