CONDITION_ERA_QUERY = """
-- Common Table Expression for cteConditionTarget
WITH cteConditionTarget AS (
  SELECT
    co.CONDITION_OCCURRENCE_ID,
    co.PERSON_ID,
    co.CONDITION_CONCEPT_ID,
    co.CONDITION_TYPE_CONCEPT_ID,
    co.CONDITION_START_DATE,
    COALESCE(co.CONDITION_END_DATE, DATE_ADD(co.CONDITION_START_DATE, 1)) AS CONDITION_END_DATE
  FROM CONDITION_OCCURRENCE co
),

-- Common Table Expression for cteEndDates
cteEndDates AS (
  SELECT
    PERSON_ID,
    CONDITION_CONCEPT_ID,
    DATE_ADD(EVENT_DATE, -30) AS END_DATE
  FROM (
    SELECT
      PERSON_ID,
      CONDITION_CONCEPT_ID,
      EVENT_DATE,
      EVENT_TYPE,
      MAX(START_ORDINAL) OVER (PARTITION BY PERSON_ID, CONDITION_CONCEPT_ID ORDER BY EVENT_DATE, EVENT_TYPE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS START_ORDINAL,
      ROW_NUMBER() OVER (PARTITION BY PERSON_ID, CONDITION_CONCEPT_ID ORDER BY EVENT_DATE, EVENT_TYPE) AS OVERALL_ORD
    FROM (
      -- Select the start dates, assigning a row number to each
      SELECT
        PERSON_ID,
        CONDITION_CONCEPT_ID,
        CONDITION_START_DATE AS EVENT_DATE,
        -1 AS EVENT_TYPE,
        ROW_NUMBER() OVER (PARTITION BY PERSON_ID, CONDITION_CONCEPT_ID ORDER BY CONDITION_START_DATE) AS START_ORDINAL
      FROM cteConditionTarget

      UNION ALL

      -- Pad the end dates by 30 to allow a grace period for overlapping ranges
      SELECT
        PERSON_ID,
        CONDITION_CONCEPT_ID,
        DATE_ADD(CONDITION_END_DATE, 30) AS EVENT_DATE,
        1 AS EVENT_TYPE,
        NULL
      FROM cteConditionTarget
    ) RAWDATA
  ) E
  WHERE (2 * E.START_ORDINAL) - E.OVERALL_ORD = 0
),

-- Common Table Expression for cteConditionEnds
cteConditionEnds AS (
  SELECT
    c.PERSON_ID,
    c.CONDITION_CONCEPT_ID,
    c.CONDITION_TYPE_CONCEPT_ID,
    c.CONDITION_START_DATE,
    MIN(e.END_DATE) AS ERA_END_DATE
  FROM cteConditionTarget c
  JOIN cteEndDates e ON c.PERSON_ID = e.PERSON_ID AND c.CONDITION_CONCEPT_ID = e.CONDITION_CONCEPT_ID AND e.END_DATE >= c.CONDITION_START_DATE
  GROUP BY
    c.PERSON_ID,
    c.CONDITION_CONCEPT_ID,
    c.CONDITION_TYPE_CONCEPT_ID,
    c.CONDITION_START_DATE
)

SELECT
  ROW_NUMBER() OVER (ORDER BY CONDITION_CONCEPT_ID) AS condition_era_id,
  PERSON_ID,
  CONDITION_CONCEPT_ID,
  MIN(CONDITION_START_DATE) AS CONDITION_ERA_START_DATE,
  ERA_END_DATE AS CONDITION_ERA_END_DATE,
  COUNT(*) AS CONDITION_OCCURRENCE_COUNT
FROM cteConditionEnds
GROUP BY
  PERSON_ID,
  CONDITION_CONCEPT_ID,
  CONDITION_TYPE_CONCEPT_ID,
  ERA_END_DATE
ORDER BY
  PERSON_ID,
  CONDITION_CONCEPT_ID
"""
