Write a query using window functions to identify the top three most frequent medical codes for each patient demographic group in a given dataset.
Use the supplied patient, medical event, and code reference tables. Exclude events without a valid patient, code, or demographic group. Return at most three codes per demographic group.
Output
- One row per demographic group and medical code, with columns
demographic_group, medical_code, occurrence_count, and code_rank.
- Include only the top three codes in each group, ranking higher frequencies first and breaking ties by
medical_code ascending.
- Order by
demographic_group ascending, then code_rank ascending.