OP10: Observation period records stratified by observation month

Counts the observation period records stratified by observation month. All possible values are summarized.

Input:
<None>

Sample query run:
The following is a sample run of the query.
Oracle only
SELECT month, sum( observations ) AS num_observations
FROM
   (
     SELECT person_id, start_date, end_date , month
          , min_count, remainder
          , start_month, DECODE( SIGN(start_month + remainder - 12),  -- LEAST emulation
                                -1, start_month + remainder,
                                12) end1
          , 1, start_month + remainder - 12 end2
          , min_count 
          + CASE WHEN MONTH >= start_month AND MONTH <= DECODE( SIGN(start_month + remainder - 12),  -- LEAST emulation
                                -1, start_month + remainder,
                                12)
                 THEN 1
                 WHEN MONTH >= 1 AND MONTH <=  start_month + remainder - 12
                 THEN 1
                 ELSE 0
             END AS observations
       FROM -- months
          ( SELECT 1 AS month FROM dual
            UNION
            SELECT 2 FROM dual
            UNION
            SELECT 3 FROM dual
            UNION
            SELECT 4 FROM dual
            UNION 
            SELECT 5 FROM DUAL
            UNION 
            SELECT 7 FROM DUAL
            UNION 
            SELECT 8 FROM DUAL
            UNION 
            SELECT 9 FROM DUAL
            UNION 
            SELECT 10 FROM DUAL
            UNION 
            SELECT 11 FROM DUAL
            UNION 
            SELECT 12 FROM DUAL
          )
      CROSS JOIN
          ( SELECT person_id, start_date, end_date , min_count, start_month, remainder
              FROM -- person with all values
                 ( SELECT person_id, observation_period_start_date start_date
                        , observation_period_end_date as end_date
                        , round(months_between( observation_period_end_date, observation_period_start_date ) ) AS months
                          /* number of complete years */
                        , floor( round(months_between( observation_period_end_date, observation_period_start_date ) ) / 12 ) AS min_count
                        , extract( month from observation_period_start_date ) start_month
                        , mod( cast(round(months_between( observation_period_end_date, observation_period_start_date ) ) AS integer), 12 ) AS remainder
                     FROM observation_period
                 )
          )
     )
 GROUP BY month order by month
Output:
Output field list:
 Field  Description
 month  Month number 1-12
 num_observations  Number of observation in a specific month

Sample output record:
 Field  Value
 month  1
 num_observations  12266979
Comments