Potentially Avoidable Hospitalisations (PAH)

lauren.brinck
30 October 2025

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 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

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

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

  1. lag facility transfer code is not missing AND event starts within 2 weeks of lag event end
  2. facility transfer from code is not missing
  3. admission source code = ‘T’ (transfer)
  4. 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:

Import lookup tables:

  1. Expand Databases in Object Explorer.
  2. Right click on IDI_Sandpit > Tasks > Import Flat File…
  3. Find location of lookup table to be imported.
  4. Provide a new table name (must be identical to names above). Choose the table schema (project).
  5. Modify columns

Parameters

The following parameters should be supplied to this module to run it in the database:

  1. {targetdb}: The SQL database on which the spell dataset is to be created.
  2. {targetschema}: The project schema under the target database into which the spell datasets are to be created.
  3. {idicleanrefresh}: The refresh version database that you want to use.
  4. {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