Module Output
SQL: [IDI_Community].[hlth_pah_indicator].pah_indicator_YYYYMM
SAS: libname pah ODBC dsn=idi_community_srvprd schema=hlth_pah_indicator; proc print data = pah.pah_indicator_YYYYMM; run ;
How to access a code module in the Data Lab: Read here
Context:
This code defines spells where clients have had a publicly funded hospital event which is considered to be a Potentially Avoidable Hospitalisation (PAH). This includes the diagnoses (ICD10 code) and the relevant ages for which it is considered a PAH event.
A child specific PAH indicator was created under the Child Youth Wellbeing Strategy. Note that this indicator is similar to the ASH (Ambulatory Sensitive Hospital admissions) measure but includes slightly different ICD10 codes and age ranges. In addition, ASH counts events while PAH counts stays (which might merge several events near in time).
Potentially Avoidable Hospitalisations (PAH) is an indicator of health-related outcomes under the Child Youth Wellbeing Strategy and a Child Poverty related indicator (CPRI) required by the Child Poverty Reduction Act 2018. The Ministry of Health is required to provide PAH data as a part of ongoing annual reporting for the Strategy and the CPRI. This PAH measure is designed to be used solely for children and youth (ages 0-25 years) and there is no corresponding PAH indicator for adults aged over 25.
The PAH definition includes hospitalisations that can be potentially avoided by:
- The provision of appropriate health care interventions and early disease management, usually delivered in primary care and community-based care settings
- Public health interventions, such as injury prevention, health promotion and immunisation
- Social policy interventions (such as income support and housing policy).
The expected business key for this spell dataset is one row per PAH hospital stay.
Key Concepts
PAH is NOT intended as an indicator of whether treatment was appropriate or hospitalisations could have been prevented in any individual case. We expect some hospitalisations for each PAH condition even if the system is working optimally. For instance, of children with asthma, some may need hospitalisation even if they receive timely and appropriate diagnosis and care in the community.
However, if the proportion increases over time, this may be an indicator that there is an issue with the availability of asthma management in primary and community care. (It may also indicate a change in other factors affecting asthma such as poor housing, circulating respiratory illness etc).
It should also be noted that a child who has several PAH events is not necessarily in poorer health than a child who has none. There are many serious childhood illnesses that are not part of the PAH definition.
Development Team
| Role | Agency | Person |
|---|---|---|
| Steward | Ministry of Health | Lauren Brinck |
| SME review | Ministry of Health | Fiona Wild |
| SME review | Ministry of Health | Laura Cleary |
| Contributor | Auckland University | Barry Milne |
| Contributor | Ministry of Health | Steven Johnson |
| Module Coder | Nicholson Consulting | Todd Nicholson |
| Module Coder | Nicholson Consulting | Hubert Zal |
Stewardship Team
| Role | Agency | Person |
|---|---|---|
| Steward | Ministry of Health | Lauren Brinck |
| SME | Ministry of Health | Fiona Wild |
| SME | Ministry of Health | Laura Cleary |
Key Business Rules
PAH Definition
The child/youth PAH definition for ages 0-25 has been constructed using the codes provided in Table 2 and 3 of The New Zealand Medical Journal article: Anderson P, Craig E, Jackson G, Jackson C. Developing a tool to monitor potentially avoidable and ambulatory care sensitive hospitalisations in New Zealand children. NZ Med J. 2012 Nov 23;125(1366):25-37. Ministry of Health have supplied an updated version (version 11).
End Date
The end_date in this table is the end of the hospital event when diagnosis took place, not the date that the chronic condition ended.
Data Consistency
- Consistent counts start in July 1999.
- As at the June 2023 refresh the data for 2023 are incomplete.
- Advice from MoH is that the hospitalisation data in NMDS generally has a one year lag. It is recommended that you look at the count of events over time to get a clear picture of the likely completeness at any point in time.
- It is likely that the end date of the reliable period will extend as the data is updated.
Age
Linking the snz_uid to the [personal_detail] table resulted in a number of individuals with missing birth dates. For this reason, the age of each individual was determined using the moh_evt_birth_year_nbr and moh_evt_birth_month_nbr from the [pub_fund_hosp_discharges_event] table. This resulted in no undefined ages.
Hospitalisation
Note that a single stay may also include more than 1 hospital event.
Child PAH
- Most PAH codes correspond to children aged 1 month to 25 years, however certain vaccine preventable diseases correspond to different age groups.
- In engaging with MoH they asked that we exclude anyone born in the month of the hospitalisation or the month before that. Note that it will exclude slightly too many people because the baby will be between 30 and 60 days old before they start counting.
- Note that PAH conditions have been defined for 0-25 year olds. The conditions listed in this module may not be Potentially Avoidable for ages over 25 years.
- From 2024 The Ministry of Health only reports PAH for ages 0-17 years
Diagnosis Definition
In some cases you may wish to limit the definition to only include the principle (primary) diagnosis. This is done in the where clause of the first query. Official stats only include the primary diagnosis.
Exclusions/Inclusions
- Transfers are excluded, i.e. when patients are transferred within and between hospitals, only the first event is counted.
- An event is defined as a transfer if NHI of the event is the same as the NHI of the lag event. (after sorting by NHI, start date, and event number)
- And at least 1 of these is true:
- lag facility transfer code is not missing AND event starts within 2 weeks of lag event end
- facility transfer from code is not missing
- admission source code = ‘T’ (transfer)
- lag moh_evt_end_type_code is in (“DA”, “DF”, “DO”, “DP”, “DT”, “DW”, “ET”) AND events starts within 2 weeks of lag event end
The moh_evt_end_type_code are:
-
DA: Discharge to an acute facility
-
DF: Statistical discharge for change in funder
-
DO: Discharge of a patient for organ donation
-
DP: Psychiatric patient transferred for further psychiatric care
-
DT: Discharge of patient to another healthcare facility
-
DW: Discharge to other service within same facility between the following types of specialty: AT&R, mental health, personal health and palliative care. Not to be used for transfer between surgical, medical and maternity services (with or without a LMC)
-
ET: Discharge from Emergency department acute facility to another healthcare facility
The full list of Event End Type Codes can be found at: www.tewhatuora.govt.nz/assets/Our-health-system/Data-and-statistics/National-Collections-Files/NCAMP/NCAMP-2024/Advisory_2024_NCAMP_Reporting-of-Event-End-Type-Code_v1.0.docx -
Privately funded events are excluded.
-
Events with missing domicile code are excluded
-
Sequelae events are excluded (Sequelae events are events that have a diagnosis resulting from a past illness, injury, or medical treatment)
Import lookup tables:
- Expand Databases in Object Explorer.
- Right click on IDI_Sandpit > Tasks > Import Flat File…
- Find location of lookup table to be imported.
- Provide a new table name (must be identical to names above). Choose the table schema (project).
- Modify columns
- change data type for
diagnosis_codeto varchar(50). - change data type for
start_age_year,end_age_year, andcode_char_lento int.
Note that this will require the correct permissions for this table and user. If this does not work then another alternative is aBULK INSERT.
Parameters
The following parameters should be supplied to this module to run it in the database:
{targetdb}: The SQL database on which the spell dataset is to be created.{targetschema}: The project schema under the target database into which the spell datasets are to be created.{idicleanrefresh}: The refresh version database that you want to use.{targetprefix}: Prefix
Dependencies
{idicleanrefresh}.[moh_clean].[pub_fund_hosp_discharges_diag]
{idicleanrefresh}.[moh_clean].[pub_fund_hosp_discharges_event]
{targetdb}.{targetschema}.[moh_PAH_lookup]
Outputs
{targetdb}.{targetschema}.[{targetprefix}_pah_indicator]
Variable Descriptions
The business key for this spell table is one row per snz_uid, moh_dia_event_id_nbr, start_date and end_date.
| Aspect | Variables | Description |
|---|---|---|
| Entity | snz_uid | A global unique identifier created by Statistics NZ. There is a snz_uid for each distinct identity in the IDI. This identifier is changed and reassigned each refresh. |
| Period | start_date | The date on which a healthcare event began. Notes: For more information about event start date refer to the data dictionary: Publications | Ministry of Health NZ . |
| end_date | The date on which a healthcare user was discharged from a facility (i.e., the date the healthcare event ended). Notes: The event end date is also known as the discharge date. The [end_date] in this table is the end of the hospital visit when diagnosis took place, NOT the date that the chronic condition ended. For information about event end date, refer to the data dictionary: Publications | Ministry of Health NZ . | |
| Event information | moh_dia_clinical_code | A code used to classify the clinical description of a condition. Notes: Clinical codes are reported in NMDS using the International Statistical Classification of Diseases and Related Health Problems, Australian modification. For more information about this code refer to the data dictionary: Publications | Ministry of Health NZ . |
| moh_dia_event_id_nbr | A Ministry of Health generated internal reference number that uniquely identifies a health event. Notes: Can be used as a key to link publicly funded hospital tables. Therefore Event ID can be used to link between this dataset and the previous one (Publicly funded hospital discharges – event information). Event ID is assigned by NMDS on load, so if an event is deleted and then reloaded, a new Event ID will be assigned. | |
| age_mnths | The patients age in months at the start of the hospital stay. | |
| moh_evt_dhb_dom_code | The code of the district health board responsible for the domicile. | |
| PAH_Category | Categorisation used in the detailed breakdown of PAH stays into diagnosis groups. | |
| PAH_SubCategory | More detailed categorisation used in the detailed breakdown of PAH stays into diagnosis groups. | |
| moh_evt_pur_unit_text | Purchase unit indicates which contract the event was funded under. Some events have a purchase unit of ‘EXCLU’ (i.e., not eligible). (This refers to the first event in a stay) | |
| moh_evt_adm_src_code | A code used to describe the nature of admission (routine or transfer) for a hospital inpatient health event. | |
| moh_evt_facility_xfer_to_code | ||
| moh_evt_end_type_code | A code identifying how a healthcare event ended. (This refers to the first event in a stay) |
Variable Descriptions - Lookup Table
| Variables | Description |
|---|---|
| diagnosis_code | A code used to classify the clinical description of a condition. |
| icd_description | Description of the ICD code. |
| PAH_Category | PAH category. |
| PAH_SubCategory | PAH subcategory. |
| start_age_year | The starting age in years. |
| end_age_year | The ending age in years. |
| code_char_len | The length of characters of the diagnosis_code. |
| injury | Indicates whether diagnosis code is related to an injury. |
Module Version & Change History
| Date | Version Comments |
|---|---|
| September 2025 | LB - Add #DiagPivot to pivot diagnosis table. removed ASH business rules from code and header. Changed public funding filter to use purchase unit and agency code. See: ?I:\MAA2020-47\0. Code Modules - Development and Library\In Development\Health Hospital PAH\2025_03_Initial_development\Changes made to IDI code 20250918.xls |
| May 2025 | HZ - Add logic to match to MOH PAH numbers using new lookup table of ICD10 codes (version 11). |
| September 2024 | TN - Add logic to match to the MoH PAH numbers. |
| June 2024 | TN - updated the header based on feedback from MoH. |
| September 2023 | TN - change the moh_dia_clinical_sys_code exclusion to allow any number 10 or greater, add to where clause to remove 1-2 month old babies, and update the PAH part of the lookup to match list supplied by MoH. |
| June 2023 | TN - Update lookup table, exclusions, and add in more columns. |
| January 2023 | TN - Add comment about primary diagnosis. |
| September 2022 | TN - Include lookup tables. |
| September 2022 | TN - Version without lookup tables. |
Code
/* Set Parameters */
/*PARAMETERS
SQLCMD only (Activate by clicking Query->SQLCMD Mode)
Already in master.sql; Uncomment when running individually */
:setvar idicleanversion "{idicleanversion}"
:setvar targetdb "{targetdb}"
:setvar targetschema "{targetschema}"
:setvar targetprefix "{targetprefix}"
/* Assign the target database to which all the components need to be created in */
USE $(targetdb);
GO
/*Extract primary diagnosis and first external cause per event*/
/*Note that the AAAAAA bits are to avoid a warning that will prevent the code from running in production*/
DROP TABLE IF EXISTS #DiagPivot_pre;
WITH ranked_diag AS (
SELECT
a.[moh_dia_event_id_nbr]
,a.[moh_dia_clinical_code]
,a.[moh_dia_diagnosis_type_code]
,a.[moh_dia_diag_sequence_code]
,ROW_NUMBER() OVER (
PARTITION BY a.[moh_dia_event_id_nbr], a.[moh_dia_diagnosis_type_code]
ORDER BY a.[moh_dia_diag_sequence_code]
) AS diag_rank
FROM [$(idicleanversion)].[moh_clean].[pub_fund_hosp_discharges_diag] a
WHERE a.[moh_dia_diagnosis_type_code] IN ('A', 'E') /*a.[moh_dia_diagnosis_type_code] IN ('A', 'E') . "A" is "Principle diagnosis" and "E" is "External cause code" */
AND CAST(a.[moh_dia_clinical_sys_code] AS INTEGER) >= 10 /* ICD-10-AM - First, second, third, sixth, eighth etc edition*/
AND a.[moh_dia_submitted_system_code] = a.[moh_dia_clinical_sys_code] /* higher accuracy when systems match */
)
SELECT
moh_dia_event_id_nbr
,MAX(CASE
WHEN moh_dia_diagnosis_type_code = 'A' THEN moh_dia_clinical_code
ELSE 'AAAAAA'
END) AS moh_dia_clinical_code
,MAX(CASE
WHEN moh_dia_diagnosis_type_code = 'E' AND diag_rank= 1 THEN moh_dia_clinical_code
ELSE 'AAAAAA'
END) AS ext_cause_code
INTO #DiagPivot_pre
FROM ranked_diag
GROUP BY [moh_dia_event_id_nbr];
/*Replace the AAAAAA values with NULLs to undo the trick we just used above*/
DROP TABLE IF EXISTS #DiagPivot;
select moh_dia_event_id_nbr,
CASE
WHEN moh_dia_clinical_code = 'AAAAAA' THEN NULL
ELSE moh_dia_clinical_code
END AS moh_dia_clinical_code,
CASE
WHEN ext_cause_code = 'AAAAAA' THEN NULL
ELSE ext_cause_code
END AS ext_cause_code
into #DiagPivot
from #DiagPivot_pre;
DROP TABLE IF EXISTS #PAH_1;
SELECT
b.[snz_uid]
,b.[moh_evt_event_id_nbr] AS moh_dia_event_id_nbr
,b.[moh_evt_evst_date] AS [start_date]
,b.[moh_evt_even_date] AS [end_date]
,a.[moh_dia_clinical_code]
,a.[ext_cause_code]
,b.[moh_evt_birth_month_nbr]
,b.[moh_evt_birth_year_nbr]
,b.[moh_evt_purchaser_code]
,b.[moh_evt_agency_code] /*check if private or public agency*/
,case when b.moh_evt_adm_type_code in ('AP','WN','WP','ZW') then 1 else 0 end as elective_ind /* elective admission type */
,case when b.moh_evt_adm_type_code in ('AA','AC','ZA','WU','RL','ZC') then 1 else 0 end as acute_ind /* this is both acute and arranged admission type */
,b.[moh_evt_dhb_dom_code] /* to identify the domicile of the patient (domicile of residence) - overseas and unknown for PAH definition is excluded */
/*result of treatment complications*/
,case when left(a.[ext_cause_code] ,3) in ( 'X58','X59','Y86','Y95','Y10','Y11','Y12','Y13','Y14','Y15','Y16','Y17','Y18','Y19','Y20','Y21','Y22','Y23','Y24','Y25','Y26','Y27','Y28','Y29','Y30','Y31','Y32','Y33','Y34')
OR ext_cause_code LIKE 'Y4%'
OR ext_cause_code LIKE 'Y5%'
OR ext_cause_code LIKE 'Y6%'
OR ext_cause_code LIKE 'Y7%'
OR ext_cause_code LIKE 'Y80%'
OR ext_cause_code LIKE 'Y81%'
OR ext_cause_code LIKE 'Y82%'
OR ext_cause_code LIKE 'Y83%'
OR ext_cause_code LIKE 'Y84%'
OR left(a.[ext_cause_code],4) in ('Y880','Y881','Y882','Y883','U900','Y899','Y872') then 1 else 0 end as med_comp
/*sequelae*/
,case when left(a.[ext_cause_code] ,4) in ('Y850','Y859','Y870','Y871','Y890','Y891') then 1 else 0 end as sequelae
,case when b.[moh_evt_purchaser_code] in ('20', '34', '35') then 1 else 0 end as purchase_code_public
,case when b.[moh_evt_agency_code] LIKE '8%' OR b.[moh_evt_agency_code] LIKE '9%' then 1 else 0 end as private_agency
/*Determine the age (in months) of the individual at time of event*/
,DATEDIFF(month, (DATEFROMPARTS(b.[moh_evt_birth_year_nbr], b.[moh_evt_birth_month_nbr], 15)), b.[moh_evt_evst_date]) AS age_mnths
,b.[moh_evt_pur_unit_text]
,b.[moh_evt_acc_flag_code]
,b.[moh_evt_adm_src_code]
,b.[moh_evt_facility_xfer_from_code]
,b.[moh_evt_facility_xfer_to_code]
,b.[moh_evt_end_type_code]
INTO #PAH_1
FROM [$(idicleanversion)].[moh_clean].[pub_fund_hosp_discharges_event] b
/*Join to discharges_events to determine snz_uid and age of each individual.*/
LEFT JOIN #DiagPivot as a
ON b.[moh_evt_event_id_nbr] = a.[moh_dia_event_id_nbr]
WHERE DATEDIFF(month, (DATEFROMPARTS(b.[moh_evt_birth_year_nbr], b.[moh_evt_birth_month_nbr], 15)), b.[moh_evt_evst_date]) >= 2 /*The official counts exclude people less than 28 days old. We cant do exactly the same exclusion but MoH have decided on this approximation*/
AND b.[moh_evt_dhb_dom_code] < 999;
/* Clear before creation */
DROP TABLE IF EXISTS #PAH;
SELECT [snz_uid]
,[moh_dia_event_id_nbr]
,[start_date]
,[end_date]
,[moh_dia_clinical_code]
,[ext_cause_code]
,[med_comp]
,[sequelae]
,[purchase_code_public]
,[private_agency]
,[age_mnths]
,[moh_evt_dhb_dom_code]
,PAH_Category
,PAH_SubCategory
,injury
,[moh_evt_pur_unit_text]
,[moh_evt_acc_flag_code]
,[moh_evt_adm_src_code]
,[moh_evt_facility_xfer_from_code]
,[moh_evt_facility_xfer_to_code]
,[moh_evt_end_type_code]
INTO #PAH
/* The following table is a lookup table.*/
FROM
(
SELECT
a.[snz_uid]
,a.[moh_dia_event_id_nbr]
,a.[start_date]
,a.[end_date]
,a.[moh_dia_clinical_code]
,a.[ext_cause_code]
,a.[med_comp]
,a.[sequelae]
,a.[purchase_code_public]
,a.[private_agency]
,a.elective_ind
,a.acute_ind
,a.moh_evt_purchaser_code
,a.age_mnths
,a.[moh_evt_dhb_dom_code]
,b.PAH_Category
,b.PAH_SubCategory
,b.injury
,a.[moh_evt_pur_unit_text]
,a.[moh_evt_acc_flag_code]
,a.[moh_evt_adm_src_code]
,a.[moh_evt_facility_xfer_from_code]
,a.[moh_evt_facility_xfer_to_code]
,a.[moh_evt_end_type_code]
FROM #PAH_1 a
LEFT JOIN [IDI_Metadata].[clean_read_CLASSIFICATIONS].[moh_PAH_lookup] b
ON SUBSTRING(a.[moh_dia_clinical_code], 1, 3) = b.[diagnosis_code]
AND b.code_char_len = 3
AND a.age_mnths between (b.start_age_year * 12) and ((b.end_age_year * 12) + 11) /*The new lookup table provides start and end age in years instead of months.*/
WHERE
SUBSTRING(a.[moh_dia_clinical_code], 1, 3) = b.[diagnosis_code]
) y;
/*Required to insert 4 length ICD10 codes seperately from 3. There are identical 3 and 4 letter [diagnosis_code] (ex. B18 and B181) which become single events when doing a LEFT JOIN. */
INSERT INTO #PAH
SELECT [snz_uid]
,[moh_dia_event_id_nbr]
,[start_date]
,[end_date]
,[moh_dia_clinical_code]
,[ext_cause_code]
,[med_comp]
,[sequelae]
,[purchase_code_public]
,[private_agency]
,[age_mnths]
,[moh_evt_dhb_dom_code]
,PAH_Category
,PAH_SubCategory
,injury
,[moh_evt_pur_unit_text]
,[moh_evt_acc_flag_code]
,[moh_evt_adm_src_code]
,[moh_evt_facility_xfer_from_code]
,[moh_evt_facility_xfer_to_code]
,[moh_evt_end_type_code]
FROM
(
SELECT
a.[snz_uid]
,a.[moh_dia_event_id_nbr]
,a.[start_date]
,a.[end_date]
,a.[moh_dia_clinical_code]
,a.[ext_cause_code]
,a.[med_comp]
,a.[sequelae]
,a.[purchase_code_public]
,a.[private_agency]
,a.elective_ind
,a.acute_ind
,a.moh_evt_purchaser_code
,a.age_mnths
,a.[moh_evt_dhb_dom_code]
,c.PAH_Category
,c.PAH_SubCategory
,c.injury
,a.[moh_evt_pur_unit_text]
,a.[moh_evt_acc_flag_code]
,a.[moh_evt_adm_src_code]
,a.[moh_evt_facility_xfer_from_code]
,a.[moh_evt_facility_xfer_to_code]
,a.[moh_evt_end_type_code]
FROM #PAH_1 a
LEFT JOIN [IDI_Metadata].[clean_read_CLASSIFICATIONS].[moh_PAH_lookup] c
ON SUBSTRING(a.[moh_dia_clinical_code], 1, 4) = c.[diagnosis_code]
AND c.code_char_len = 4
AND a.age_mnths between (c.start_age_year * 12) and ((c.end_age_year * 12) + 11)/*The new lookup table provides start and end age in years instead of months.*/
WHERE SUBSTRING(a.[moh_dia_clinical_code], 1, 4) = c.[diagnosis_code]
) x;
/*Required to insert 5 length ICD10 codes seperately from 3 and 4. There are identical 3 and 4 letter [diagnosis_code] (ex. B18 and B181) which become single events when doing a LEFT JOIN. */
INSERT INTO #PAH
SELECT [snz_uid]
,[moh_dia_event_id_nbr]
,[start_date]
,[end_date]
,[moh_dia_clinical_code]
,[ext_cause_code]
,[med_comp]
,[sequelae]
,[purchase_code_public]
,[private_agency]
,[age_mnths]
,[moh_evt_dhb_dom_code]
,PAH_Category
,PAH_SubCategory
,injury
,[moh_evt_pur_unit_text]
,[moh_evt_acc_flag_code]
,[moh_evt_adm_src_code]
,[moh_evt_facility_xfer_from_code]
,[moh_evt_facility_xfer_to_code]
,[moh_evt_end_type_code]
FROM
(
SELECT
a.[snz_uid]
,a.[moh_dia_event_id_nbr]
,a.[start_date]
,a.[end_date]
,a.[moh_dia_clinical_code]
,a.[ext_cause_code]
,a.elective_ind
,a.acute_ind
,a.[med_comp]
,a.[sequelae]
,a.[purchase_code_public]
,a.[private_agency]
,a.moh_evt_purchaser_code
,a.age_mnths
,a.[moh_evt_dhb_dom_code]
,d.PAH_Category
,d.PAH_SubCategory
,d.injury
,a.[moh_evt_pur_unit_text]
,a.[moh_evt_acc_flag_code]
,a.[moh_evt_adm_src_code]
,a.[moh_evt_facility_xfer_from_code]
,a.[moh_evt_facility_xfer_to_code]
,a.[moh_evt_end_type_code]
FROM #PAH_1 a
LEFT JOIN [IDI_Metadata].[clean_read_CLASSIFICATIONS].[moh_PAH_lookup] d
ON SUBSTRING(a.[moh_dia_clinical_code], 1, 5) = d.[diagnosis_code]
AND d.code_char_len = 5
AND a.age_mnths between (d.start_age_year * 12) and ((d.end_age_year * 12) + 11) /*The new lookup table provides start and end age in years instead of months.*/
WHERE SUBSTRING(a.[moh_dia_clinical_code], 1, 5) = d.[diagnosis_code]
) x;
/* Add index */
CREATE CLUSTERED INDEX my_index_name ON #PAH ([snz_uid]);
/* Compress final table to save space */
ALTER TABLE #PAH REBUILD PARTITION = ALL WITH (DATA_COMPRESSION = PAGE);
/*Identify transfers*/
/*Firstly lag the variables required*/
DROP TABLE IF EXISTS #PAH_lag;
SELECT
*,
lag([snz_uid]) over(order by [snz_uid], [start_date], [end_date], [moh_dia_event_id_nbr]) as prev_snz_uid,
lag([end_date]) over(order by [snz_uid], [start_date], [end_date], [moh_dia_event_id_nbr]) as prev_end_date,
lag(moh_evt_end_type_code) over(order by [snz_uid], [start_date], [end_date], [moh_dia_event_id_nbr]) as prev_moh_evt_end_type_code,
lag(moh_evt_facility_xfer_to_code) over(order by [snz_uid], [start_date], [end_date], [moh_dia_event_id_nbr]) as prev_moh_evt_facility_xfer_to_code
INTO #PAH_lag
FROM #PAH;
/*Identify the transfer and flag it*/
DROP TABLE IF EXISTS #PAH_lag_trans;
SELECT
*,
case
when snz_uid = prev_snz_uid and (
/*Check if event start date is less than 14 days since lag event end date and (lag event has a facility transfer code recorded or a transfer end type recorded)*/
(
[start_date] < [prev_end_date] OR
[start_date] <= DATEADD(DAY, 14, CAST([prev_end_date] AS DATE))
) and
(
prev_moh_evt_facility_xfer_to_code is not NULL or
prev_moh_evt_end_type_code in ('DA', 'DF', 'DO', 'DP', 'DT', 'DW', 'ET')
)
or
/*Check if event has a transfer from code recorded*/
moh_evt_facility_xfer_from_code is not NULL or
/*Check if event has admission source recorded as transfer*/
moh_evt_adm_src_code = 'T'
)
then 1
else 0
end as trans
INTO #PAH_lag_trans
FROM #PAH_lag;
/*Remove the transfers and hospitalisations that were a results of medical treatment or sequelae, and remove privately funded PAHs*/
DROP TABLE IF EXISTS #PAH_final;
SELECT
*
INTO #PAH_final
FROM #PAH_lag_trans
WHERE trans = 0
AND med_comp= 0
AND sequelae= 0
AND purchase_code_public =1
AND private_agency = 0;
/*Write the proper table*/
DROP TABLE IF EXISTS #final_PAH;
SELECT
[snz_uid]
,[moh_dia_event_id_nbr]
,[start_date]
,[end_date]
,[moh_dia_clinical_code]
,[age_mnths]
,[moh_evt_dhb_dom_code]
,PAH_Category
,PAH_SubCategory
,[moh_evt_pur_unit_text]
,[moh_evt_acc_flag_code]
,[moh_evt_adm_src_code]
,[moh_evt_facility_xfer_to_code]
,[moh_evt_end_type_code]
INTO #final_PAH
FROM #PAH_final;
DROP TABLE IF EXISTS [$(targetdb)].[$(targetschema)].[$(targetprefix)_PAH];
CREATE TABLE [$(targetdb)].[$(targetschema)].[$(targetprefix)_PAH] (
snz_uid int NOT NULL,
moh_dia_event_id_nbr int NOT NULL,
[start_date] date NULL,
end_date date NULL,
moh_dia_clinical_code varchar(8) NULL,
age_mnths int NULL,
moh_evt_dhb_dom_code char(3) NULL,
PAH_Category varchar(100) NULL,
PAH_SubCategory varchar(100) NULL,
moh_evt_pur_unit_text varchar(10) NULL,
moh_evt_acc_flag_code char(1) NULL,
moh_evt_adm_src_code char(1) NULL,
moh_evt_facility_xfer_to_code char(4) NULL,
moh_evt_end_type_code char(4) NULL
);
INSERT INTO [$(targetdb)].[$(targetschema)].[$(targetprefix)_PAH]
SELECT
snz_uid,
moh_dia_event_id_nbr,
[start_date],
end_date,
moh_dia_clinical_code,
age_mnths,
moh_evt_dhb_dom_code,
PAH_Category,
PAH_SubCategory,
moh_evt_pur_unit_text,
moh_evt_acc_flag_code,
moh_evt_adm_src_code,
moh_evt_facility_xfer_to_code,
moh_evt_end_type_code
FROM #final_PAH;
SELECT
*
FROM #final_PAH