Intellectual (Learning) Disability - Code Module

adelaide.wilson
26 May 2025

Output path

SQL:[IDI_Community].[dsbl_intellectual_disability].[intellectual_disability_YYYYMM]
SAS: libname cmid dsn=idi_community_srvprd schema=dsbl_intellectual_disability; run ;
How to access a code module in the Data Lab:Read here

Description

The purpose of this code module is to identify individuals in New Zealand in the IDI who have a recorded diagnosis of intellectual disability or records indicating an intellectual disability diagnosis is likely (for example a recorded residential history for persons with intellectual disability).

The dataset will list individuals, the earliest event when an individual has a recorded/likely diagnosis of intellectual disability in the IDI, date of the earliest event, the individual’s age and whether they are alive at the time of the IDI refresh. For those individuals who have died, the dataset lists a date of death and age at death.

This module is not intended to be used to give a true prevalence rate of people in New Zealand with intellectual disability due to limitations of the datasets included in the IDI. The code module allows researchers to have a consistent way of identifying intellectually disabled New Zealanders and will allow for comparisons of outcomes for people with intellectual disability and people without intellectual disability.

Key Concepts

Business history

Code history and ICD code notes

ICD codes used are based on the ICD clinical code system for the earliest date of data as per Health New Zealand (HNZ) | Te Whatu Ora best practice. This means ICD-9-CM-A codes have been used in line with the start of the health-related datasets in the IDI.

On advice from HNZ clinical coding/classification staff, codes have first been looked up directly in ICD-10-AM 12th Edition (current Edition used), then back mapped to ICD-10-AM 1st Edition and then back mapped to ICD-9-CM-A codes.

Notes for specific datasets

References

  1. Beltran-Castillon L and McLeod K (2023) From Data to Dignity: Health and Wellbeing Indicators for New Zealanders with Intellectual Disability. Published: IHC, Kōtātā Insight
  2. Stats NZ (2025) Household Disability Survey 2023 - findings, definitions, and design summary.

Community of Interest

Domain Agency Person
Initial code Social Investment Agency (SIA) Craig Wright
Module coder Whaikaha - Ministry of Disabled People Adelaide Wilson
Module coder Nicholson Consulting Sarah Underwood
Lead SME/Policy Whaikaha - Ministry of Disabled People Michelle Gezentsvey, Claire Bretherton

Key business rules

Dataset name Diagnosis definition Dataset time period
Accident Compensation Corporation (ACC) Injury Claims Data Recorded as having an ACC read code on the ACC45 claim form of: 1974 -
‘E3…’ (Intellectual disability),
‘E30..’ (Mild intellectual disability),
‘E310.’ (Moderate intellectual disability),
‘E311.’ (Severe intellectual disability), or
‘E312.’ (Profound intellectual disability).
Publicly funded hospital discharges (NMDS) A publicly funded hospital discharge with a primary or secondary ICD-9-CM-A diagnosis code of: 1988 -
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181(Severe mental retardation),
3182 (Profound mental retardation), or
319 (Unspecified mental retardation).
Privately funded hospital discharges (NMDS) A privately funded hospital discharge with a primary or secondary ICD-9-CM-A diagnosis code of: 2001 -
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181(Severe mental retardation),
3182 (Profound mental retardation), or
319 (Unspecified mental retardation),
or an ICD-10-AM diagnosis code of:
F700 (Mild intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F701 (Mild intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F708 (Mild intellectual development disorder, other impairments of behaviour),
F709 (Mild intellectual development disorder without mention of impairment of behaviour),
F710 (Moderate intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F711 (Moderate intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F718 (Moderate intellectual development disorder, other impairments of behaviour),
F719 (Moderate intellectual development disorder without mention of impairment of behaviour),
F720 (Severe intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F721 (Severe intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F728 (Severe intellectual development disorder, other impairments of behaviour),
F729 (Severe intellectual development disorder without mention of impairment of behaviour),
F730 (Profound intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F731 (Profound intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F738 (Profound intellectual development disorder, other impairments of behaviour),
F739 (Profound intellectual development disorder without mention of impairment of behaviour),
F780 (Other intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F781 (Other intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F788 (Other intellectual development disorder, other impairments of behaviour),
F789 (Other intellectual development disorder without mention of impairment of behaviour),
F790 (Unspecified intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F791 (Unspecified intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F798 (Unspecified intellectual development disorder, other impairments of behaviour), or
F799 (Unspecified intellectual development disorder without mention of impairment of behaviour).
Mortality Collection (MORT) Identified as an underlying or contributing cause of death with an ICD-9-CM-A diagnosis code of: 1988 -
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181(Severe mental retardation),
3182 (Profound mental retardation) or
319 (Unspecified mental retardation),
or an ICD-10-AM diagnosis code of:
F700 (Mild intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F701 (Mild intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F708 (Mild intellectual development disorder, other impairments of behaviour),
F709 (Mild intellectual development disorder without mention of impairment of behaviour),
F710 (Moderate intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F711 (Moderate intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F718 (Moderate intellectual development disorder, other impairments of behaviour),
F719 (Moderate intellectual development disorder without mention of impairment of behaviour),
F720 (Severe intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F721 (Severe intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F728 (Severe intellectual development disorder, other impairments of behaviour),
F729 (Severe intellectual development disorder without mention of impairment of behaviour),
F730 (Profound intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F731 (Profound intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F738 (Profound intellectual development disorder, other impairments of behaviour),
F739 (Profound intellectual development disorder without mention of impairment of behaviour),
F780 (Other intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F781 (Other intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F788 (Other intellectual development disorder, other impairments of behaviour),
F789 (Other intellectual development disorder without mention of impairment of behaviour),
F790 (Unspecified intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F791 (Unspecified intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F798 (Unspecified intellectual development disorder, other impairments of behaviour), or
F799 (Unspecified intellectual development disorder without mention of impairment of behaviour).
Disability Support Services database (SOCRATES) Recorded as having intellectual disability in the Referral Diagnosis/Health Condition field with the code of: 1998 -
1208 (Intellectual Disability (ID), type not specified), or
1299 (Other intellectual, learning or developmental disorder (specify)).
Programme for the Integration of Mental Health Data (PRIMHD) A diagnosis in the DSM-IV classification system in secondary mental health and addiction services with a code of: 2009 -
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181 (Severe mental retardation),
3182 (Profound mental retardation), or
319 (Mental retardation, severity unspecified),
or an ICD-10-AM diagnosis code of:
F700 (Mild intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F701 (Mild intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F708 (Mild intellectual development disorder, other impairments of behaviour),
F709 (Mild intellectual development disorder without mention of impairment of behaviour),
F710 (Moderate intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F711 (Moderate intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F718 (Moderate intellectual development disorder, other impairments of behaviour),
F719 (Moderate intellectual development disorder without mention of impairment of behaviour),
F720 (Severe intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F721 (Severe intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F728 (Severe intellectual development disorder, other impairments of behaviour),
F729 (Severe intellectual development disorder without mention of impairment of behaviour),
F730 (Profound intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F731 (Profound intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F738 (Profound intellectual development disorder, other impairments of behaviour),
F739 (Profound intellectual development disorder without mention of impairment of behaviour),
F780 (Other intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F781 (Other intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F788 (Other intellectual development disorder, other impairments of behaviour),
F789 (Other intellectual development disorder without mention of impairment of behaviour),
F790 (Unspecified intellectual development disorder with the statement of no, or minimal, impairment of behaviour),
F791 (Unspecified intellectual development disorder, significant impairment of behaviour requiring attention or treatment),
F798 (Unspecified intellectual development disorder, other impairments of behaviour), or
F799 (Unspecified intellectual development disorder without mention of impairment of behaviour).
Mental Health Information National Collection (MHINC) A diagnosis in the DSM-IV classification system in secondary mental health and addiction services with a code of: July 2001 - 2008
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181 (Severe mental retardation),
3182 (Profound mental retardation), or
319 (Mental retardation, severity unspecified),
or an ICD-9-CM-A diagnosis code of:
317 (Mild mental retardation),
3180 (Moderate mental retardation),
3181(Severe mental retardation),
3182 (Profound mental retardation), or
319 (Unspecified mental retardation).
InterRAI data A registration in the InterRAI dataset a recorded residential history for persons with intellectual disability. 2014 -
Ministry of Social Development Income Support data A diagnosis of intellectual disability recorded on a medical certificate provided for the purposes of establishing eligibility for benefits or other Ministry of Social Development payments. 1992 -
Oranga Tamariki Gateway Assessments Data A need type of intellectual disability in a Gateway Assessment. 2013 -

Data quality and other known issues

  1. Not all individuals in New Zealand diagnosed with intellectual disability will be identified in this module. The module requires that the individual has had an ACC claim form, hospital discharge events, receivedmental health or Disability Support Services, income support/benefit eligibility, an Oranga Tamariki gateway assessment, been recorded in interRAI data as having a residential history for persons with intellectual disability, or had their death recorded, where the diagnosis of intellectual disability has been specified.

  2. Datasets included have different lag times for having updated data available in the IDI. This means the completeness of the data at the time of analysis will depend on the lag time of the different datasets.

  3. Individuals identified in the SOCRATES disability dataset do not always appear in the referral or needs assessment datasets as well. Where an individual is only identified through the SOCRATES disability dataset there is no associated event date. In this case a proxy date of ‘3999-12-31’ will be seen in the final table.

  4. Registerable stillbirths are included in the mortality dataset.

Comparison against other sources

Parameters

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

  1. {targetdb}: The SQL database on which the datasets are to be created.
  2. {idicleanversion}: The IDI Clean version that the datasets need to be based on.
  3. {targetschema}: The project schema under the target database into which the datasets are to be created.

Dependencies

{idicleanrefresh}.[acc_clean].[claims]
{idicleanrefresh}.[acc_clean].[medical_codes]
{idicleanrefresh}.[moh_clean].[pub_fund_hosp_discharges_diag]
{idicleanrefresh}.[moh_clean].[pub_fund_hosp_discharges_event]
{idicleanrefresh}.[moh_clean].[priv_fund_hosp_discharges_diag]
{idicleanrefresh}.[moh_clean].[priv_fund_hosp_discharges_event]
{idicleanrefresh}.[moh_clean].[mortality_diagnosis]
{idicleanrefresh}.[moh_clean].[mortality_registrations]
{idicleanrefresh}.[moh_clean].[pop_cohort_demographics]
{idicleanrefresh}.[security].[concordance]
{idicleanrefresh}.[moh_clean].[interrai]
{idicleanrefresh}.[msd_clean].[msd_incapacity]
{idicleanrefresh}.[data].[personal_detail]
{idicleanrefresh}.[dia_clean].[deaths]

The following IDI_Adhoc are the most recent versions for this current refresh but changes to the code will need to be made as new datasets are uploaded into the IDI.

[IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_disability_2022]
[IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_needs_assessment_2022]
[IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_referral_2022]
[IDI_Adhoc].[clean_read_MOH_PRIMHD].[primhd_diagnoses_202502]
[IDI_Adhoc].[clean_read_MOH_PRIMHD].[moh_primhd_mhinc]
[IDI_Adhoc].[clean_read_CYF].[cyf_gateway_cli_needs]

Outputs

{targetdb}.{targetschema}.intellectual_disability
Column name Description
snz_uid The unique Stats NZ person identifier for the the individual
type A string indicating which condition or disability this table has identified (hard-coded to “ID”)
entity A string indicating the organisation or provider ID that has provided a service for mental health services, where relevant
source_table A string that states the data source for the earliest record of diagnosis for an individual in the IDI
min_date The earliest record of diagnosis for an individual in the IDI (Note: not a date of diagnosis or onset of a condition)
snz_sex_gender_code Code for an individual’s gender
snz_birth_month_nbr Month of an individual’s birth
snz_birth_year_nbr Year of an individual’s birth
snz_birth_date_proxy Proxy date of an individual’s birth
age Age of an individual at the time of the IDI refresh
death_status A binary indicator indicating whether an individual is recorded dead (value = 1) or alive (value = 0) at the time of refresh
snz_deceased_year_nbr Year of an individual’s death (if relevant)
snz_deceased_month_nbr Month of an individual’s death (if relevant)
dod Date of death (if relevant)
age_at_death Age of an individual at death (if relevant)

Variable descriptions

Granularity:
One row represents an individual, the earliest identification of their diagnosis in the IDI, birthdate, gender and death (if applicable).

Module Version & Change History

Date Version Comments
26 May 2025 Initial Version based on specifications from Commissioning document
09 June 2025 1.1 Update to ACC variable with 202506 refresh. acc_med_read_code updated to acc_med_injury_code and acc_cla_read_code to acc_cla_primary_inj_code with acc_cla_primary_inj_type_code added.
31 October 2025 1.2 Update to MoH publicly funded hospital discharge variable with 20510 refresh. Converted moh_evt_evst_date from datetime to date.

Code


/*Set Parameters*/
/*Ref date should be the 15th of the month of the refresh used*/
:setvar targetdb "targetdb"
:setvar targetschema "targetschema" 
:setvar idicleanversion "idicleanversion"
:setvar refdate "refdate"
:setvar idimetadataversion "idimetadataversion"

USE $(targetdb);
GO

/*ACC claims with a code that includes intellectual disability disorder(mild, moderate, severe, profound)*/

DROP TABLE IF EXISTS #acc_id;
SELECT
c.snz_uid
,'ACC' AS source_table
,c.code
,c.date AS event_date
,CAST(NULL AS VARCHAR(10)) AS entity
INTO #acc_id
FROM 
(
SELECT 
[snz_uid]
,[acc_cla_accident_date] AS date
,[acc_cla_primary_inj_code] AS code
FROM [$(idicleanversion)].[acc_clean].[claims]
     WHERE ([acc_cla_primary_inj_code] IN ('E312.','E311.','E310.','E30..', 'E3...') AND [acc_cla_primary_inj_type_code] = 'Read Code')
UNION ALL  
SELECT 
b.snz_uid
,b.acc_cla_accident_date AS date
,a.[acc_med_injury_code] AS code
FROM  [$(idicleanversion)].[acc_clean].[medical_codes] AS a
      LEFT JOIN  [$(idicleanversion)].[acc_clean].[claims] AS b ON a.[snz_acc_claim_uid] = b.[snz_acc_claim_uid]
	  WHERE a.[acc_med_injury_code] IN ('E312.','E311.','E310.','E30..', 'E3...')
      ) AS c;

/*Public hospital discharges where clinical code matches a diagnosis of intellectual disability*/

DROP TABLE IF EXISTS #moh_pub_id; 
SELECT
b.snz_uid
,'MOH_PUB' AS source_table
,a.[moh_dia_submitted_system_code] AS code_sys
,a.[moh_dia_diagnosis_type_code]
,a.[moh_dia_event_id_nbr]
,a.[moh_dia_clinical_code]
,b.moh_evt_birth_year_nbr
,CAST (b.[moh_evt_evst_date] AS DATE) AS event_date
,CAST (NULL AS VARCHAR(10)) AS entity
INTO #moh_pub_id
FROM [$(idicleanversion)].[moh_clean].[pub_fund_hosp_discharges_diag] AS a
     LEFT JOIN [$(idicleanversion)].[moh_clean].[pub_fund_hosp_discharges_event] AS b ON a.moh_dia_event_id_nbr = b.moh_evt_event_id_nbr
	 WHERE ((SUBSTRING(a.[moh_dia_clinical_code],1,3) IN ('317','319') OR SUBSTRING (a.[moh_dia_clinical_code],1,4) IN ('3180','3181', '3182')) AND a.[moh_dia_clinical_sys_code] = '06' AND a.[moh_dia_diagnosis_type_code] IN ('A','B'));
	

/*Private hospital discharges where clinical code matches a diagnosis of intellectual disability*/

DROP TABLE IF EXISTS #moh_pri_id;
SELECT 
b.snz_uid
,'MOH_PRI' AS source_table
,a.[moh_pri_diag_event_id_nbr]
,a.[moh_pri_diag_clinic_sys_code]
,a.[moh_pri_diag_sub_sys_code]
,a.[moh_pri_diag_diag_type_code]
,a.[moh_pri_diag_clinic_code] 
,b.[moh_pri_evt_start_date] AS event_date
,CAST (NULL AS VARCHAR(10)) AS entity
INTO #moh_pri_id
FROM [$(idicleanversion)].[moh_clean].[priv_fund_hosp_discharges_diag] AS a
     LEFT JOIN [$(idicleanversion)].[moh_clean].[priv_fund_hosp_discharges_event] AS b ON a.moh_pri_diag_event_id_nbr = b.moh_pri_evt_event_id_nbr
     WHERE ((SUBSTRING(a.[moh_pri_diag_clinic_code],1,3) IN ('317, 319') OR SUBSTRING(a.[moh_pri_diag_clinic_code],1,4) IN ('3180','3181','3182')) AND a.[moh_pri_diag_clinic_sys_code] = '06' AND a.[moh_pri_diag_diag_type_code] IN ('A','B'))
     OR (SUBSTRING(a.[moh_pri_diag_clinic_code],1,4) IN ('F700','F701','F708','F709','F710','F711','F718','F719','F720','F721','F728','F729','F730','F731','F738','F739','F780','F781','F788','F789','F790','F791','F798','F799') AND a.[moh_pri_diag_clinic_sys_code] >= '10' AND a.[moh_pri_diag_diag_type_code] IN ('A','B'));

/*Registrations in the mortality dataset where clinical code matches a diagnosis of intellectual disability*/

DROP TABLE IF EXISTS #mos_id;
SELECT
 b.[snz_uid]
,b.[snz_moh_uid]
,'MOH_MOS' AS source_table
,DATEFROMPARTS(b.moh_mor_birth_year_nbr,b.moh_mor_birth_month_nbr,15) AS event_date
,a.[moh_mort_diag_clinical_code] AS code
,a.[moh_mort_diag_clinic_type_code]
,a.[moh_mort_diag_clinic_sys_code]
,a.[moh_mort_diag_diag_type_code]
,CAST (NULL AS VARCHAR(10)) AS entity
INTO #mos_id
FROM [$(idicleanversion)].[moh_clean].[mortality_diagnosis] AS a
      LEFT JOIN [$(idicleanversion)].[moh_clean].[mortality_registrations] AS b  ON a.snz_dia_death_reg_uid = b.snz_dia_death_reg_uid
      WHERE ((SUBSTRING (a.[moh_mort_diag_clinical_code],1,4) IN ('3180, 3181, 3182') OR SUBSTRING (a.[moh_mort_diag_clinical_code],1,3) IN ('317','319')) AND a.[moh_mort_diag_clinic_sys_code] = '06')
	  OR (SUBSTRING(a.[moh_mort_diag_clinical_code],1,4) IN ('F700','F701','F708','F709','F710','F711','F718','F719','F720','F721','F728','F729','F730','F731','F738','F739','F780','F781','F788','F789','F790','F791','F798','F799')  AND a.[moh_mort_diag_clinic_sys_code]>='10');

 /* Individuals in the Ministry of Health SOCRATES database with code 1208 or 1299. Date can either be first contact date or referral date.
Where an individual appears only in the disability table but not the needs assessment or referral table, an event date of 3999-12-31 is added.
This date will be removed in the collation process if the individual appears in other datasets with an earlier event_date or kept if the 
diagnosis table is the only record for the individual*/

DROP TABLE IF EXISTS #moh_soc_id;
SELECT
DISTINCT
b.snz_uid
,'SOC' AS source_table
,CASE WHEN CAST(SUBSTRING(c.[FirstContactDate],1,7) AS date) IS NOT NULL THEN CAST(SUBSTRING(c.[FirstContactDate],1,7) AS date) 
	  WHEN CAST(SUBSTRING(e.[ReferralDate],1,7) AS date) IS NOT NULL THEN CAST(SUBSTRING(e.[ReferralDate],1,7) AS date)
	  WHEN CAST(SUBSTRING(e.[ReferralDate],1,7) AS date) IS NULL AND CAST(SUBSTRING(c.[FirstContactDate],1,7) AS date) IS NULL THEN '3999-12-31'
	  END AS event_date
,CAST (a.code as VARCHAR(7)) AS code
,a.[Description] 
,CAST (NULL AS VARCHAR(10)) AS entity
INTO #moh_soc_id
FROM [IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_disability_2022] AS a 
     LEFT JOIN [$(idicleanversion)].[moh_clean].[pop_cohort_demographics] AS b ON a.snz_moh_uid = b.snz_moh_uid 
     LEFT JOIN (SELECT DISTINCT snz_moh_uid,[FirstContactDate] FROM [IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_needs_assessment_2022] ) AS c ON a.snz_moh_uid=c.snz_moh_uid 
     LEFT JOIN (SELECT DISTINCT snz_moh_uid,[ReferralDate] FROM [IDI_Adhoc].[clean_read_MOH_SOCRATES].[moh_referral_2022]) as e ON a.snz_moh_uid=e.snz_moh_uid
     WHERE code IN ('1208','1299');

/*Intellectual disability diagnosis in PRIMHD diagnosis data*/ 

DROP TABLE IF EXISTS #moh_PRIMHD_id;
SELECT
b.snz_uid
,a.[snz_moh_uid]
,'MOH_PRIMHD' AS source_table
,CAST (a.[organisation_id] AS VARCHAR(10)) AS entity
,a.[classification_code_id]
,a.[diagnosis_type]
,CONVERT(date,a.[classification_start_date],103) AS event_date
,a.[clinical_coding_system_id]
,a.[clinical_code] AS code
INTO #moh_PRIMHD_id
FROM [IDI_Adhoc].[clean_read_MOH_PRIMHD].[primhd_diagnoses_202502] AS a
     LEFT JOIN [$(idicleanversion)].[moh_clean].[pop_cohort_demographics] AS b ON a.snz_moh_uid = b.snz_moh_uid
      WHERE ((SUBSTRING(a.[clinical_code],1,3) IN ('317','319')  AND a.[clinical_coding_system_id]='07') OR
	(SUBSTRING(a.[clinical_code],1,4) IN ('3180','3181','3182')  AND a.[clinical_coding_system_id]='07') OR
	(SUBSTRING(a.[clinical_code],1,4) IN ('F700','F701','F708','F709','F710','F711','F718','F719','F720','F721','F728','F729','F730','F731','F738','F739','F780','F781','F788','F789','F790','F791','F798','F799')  AND a.[clinical_coding_system_id]>='10'));

/* Intellectual disability diagnosis in PRIMHD MHINC data*/

DROP TABLE IF EXISTS #moh_mhinc_id;
SELECT 
b.snz_uid
,'MOH_MHINC' AS source_table
,CAST (a.[organisation_id] AS VARCHAR(10)) AS entity
,a.[classification_start] AS event_date
,a.[clinical_coding_system_id]
,a.[clinical_code] AS code
,a.[diagnosis_type]
INTO #moh_mhinc_id
FROM [IDI_Adhoc].[clean_read_MOH_PRIMHD].[moh_primhd_mhinc] AS a
     LEFT JOIN [$(idicleanversion)].[moh_clean].[pop_cohort_demographics] AS b ON a.snz_moh_uid = b.snz_moh_uid
     WHERE ((SUBSTRING(a.[clinical_code],1,3) IN ('317','319')  AND a.[clinical_coding_system_id]='06') OR 
    (SUBSTRING([clinical_code],1,4) IN ('3180','3181','3182')  AND a.[clinical_coding_system_id]='06') OR
	(SUBSTRING(a.[clinical_code],1,3) IN ('317','319')  AND a.[clinical_coding_system_id]='07') OR
	(SUBSTRING(a.[clinical_code],1,4) IN ('3180','3181','3182')  AND a.[clinical_coding_system_id]='07'));

/* Registrations in the interrai dataset with records of residential history for persons with intellectual disability*/

DROP TABLE IF  EXISTS #moh_irai_id;
SELECT [snz_uid]
,[moh_irai_res_hist_intellect_ind] as code
,[moh_irai_assessment_date] as event_date
,CAST (NULL AS VARCHAR(10)) AS entity
,'IRAI' AS source_table
INTO #moh_irai_id
FROM [$(idicleanversion)].[moh_clean].[interrai]
     WHERE [moh_irai_res_hist_intellect_ind] > 0;

/* Intellectual disability recorded on medical certificates */
  
DROP TABLE IF EXISTS #msd_incp_id;
SELECT
[snz_uid]
,code_raw AS code
,from_date AS event_date
,'MSD_INCP' AS source_table
,CAST (NULL AS VARCHAR (10)) AS entity
INTO #msd_incp_id
FROM
((
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incrsn_code] AS code_raw
	  ,'I' AS type
  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
UNION
(
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incrsn95_1_code] AS code_raw
	  ,'1' AS type

  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
UNION
(
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incrsn95_2_code] AS code_raw
	  ,'2' AS type
 
  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
UNION
(
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incrsn95_3_code] AS code_raw
	  ,'3' AS type
    
  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
UNION
(
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incrsn95_4_code] AS code_raw
	  ,'4' AS type
 
  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
UNION
(
SELECT [snz_uid]
      ,[msd_incp_incp_from_date] AS from_date
      ,[msd_incp_incp_to_date] AS to_date
      ,[msd_incp_incapacity_code] AS code_raw
	  ,'T' AS type
    
  FROM [$(idicleanversion)].[msd_clean].[msd_incapacity]
)
) AS a
      WHERE code_raw IS NOT NULL AND code_raw !='000' AND code_raw IN ('008','164');

/* intellectual disability as a client need in gateway assesssments*/

DROP TABLE IF EXISTS #cyf_gateway_id;
SELECT       
b.snz_uid
,a.snz_msd_uid
,a.[need_type_code]
,a.[needs_desc]
,a.[need_category_code] AS code
,a.[needs_cat_desc]
,needs_created_date AS event_date
,'CYF' AS source_table
, CAST (NULL AS VARCHAR (10)) AS entity
INTO #cyf_gateway_id
FROM [IDI_Adhoc].[clean_read_CYF].[cyf_gateway_cli_needs] AS a 
     LEFT JOIN [$(idicleanversion)].security.concordance AS b  ON a.snz_msd_uid = b.snz_msd_uid
     WHERE need_type_code = 'INT';

/* collate data from all sources into one table*/

DROP TABLE IF EXISTS #id;
SELECT
a.snz_uid 
,MIN(event_date) AS min_date
,source_table
,entity
INTO #id
FROM
(
SELECT  snz_uid, event_date, source_table, entity FROM #mos_id
UNION ALL
SELECT  snz_uid, event_date, source_table, entity FROM #moh_pub_id
UNION ALL
SELECT  snz_uid, event_date, source_table, entity FROM #moh_pri_id
UNION ALL
SELECT  snz_uid, event_date, source_table, entity FROM #moh_soc_id
UNION ALL
SELECT  snz_uid, event_date, source_table, entity FROM #moh_mhinc_id
UNION ALL
SELECT  snz_uid, event_date, source_table, entity FROM #moh_PRIMHD_id
UNION ALL
SELECT snz_uid, event_date, source_table, entity FROM #cyf_gateway_id
UNION ALL
SELECT snz_uid, event_date, source_table, entity FROM #msd_incp_id
UNION ALL
SELECT snz_uid, event_date, source_table, entity FROM #moh_irai_id
UNION ALL
SELECT snz_uid, event_date, source_table, entity FROM #acc_id
) AS a
GROUP BY snz_uid
, source_table
, entity;

/* subset of individuals who are deceased and are in death data*/

DROP TABLE IF EXISTS #id_dd;
SELECT 
a.*
,b.snz_birth_month_nbr
,b.snz_birth_year_nbr
,b.snz_sex_gender_code
,b.snz_deceased_year_nbr
,b.snz_deceased_month_nbr
,b.snz_birth_date_proxy
,NULL AS age
,DATEFROMPARTS(b.snz_deceased_year_nbr, b.snz_deceased_month_nbr, 15) AS dod
,'ID' AS [type]
INTO #id_dd
FROM #id as a
     INNER JOIN [$(idicleanversion)].[data].[personal_detail] AS b ON a.snz_uid = b.snz_uid
     WHERE a.snz_uid IN (SELECT DISTINCT snz_uid FROM [$(idicleanversion)].[dia_clean].[deaths])
     AND b.snz_deceased_year_nbr IS NOT NULL;

/* subset of individuals who are deceased but not in death data*/

DROP TABLE IF EXISTS #id_od;
SELECT
a.*
,b.snz_birth_month_nbr
,b.snz_birth_year_nbr
,b.snz_sex_gender_code
,b.snz_deceased_year_nbr
,b.snz_deceased_month_nbr
,b.snz_birth_date_proxy
,NULL AS age
,DATEFROMPARTS(b.snz_deceased_year_nbr, b.snz_deceased_month_nbr, 15) AS dod
,'ID' AS [type]
INTO #id_od
FROM #id AS a
     INNER JOIN [$(idicleanversion)].[data].[personal_detail] AS b ON a.snz_uid = b.snz_uid
     WHERE a.snz_uid NOT IN (SELECT DISTINCT snz_uid FROM [$(idicleanversion)].[dia_clean].[deaths])
     AND b.snz_deceased_year_nbr IS NOT NULL;

/* subset of individuals who are alive*/

DROP TABLE IF EXISTS #id_ad;
SELECT 
a.*
,b.snz_birth_month_nbr
,b.snz_birth_year_nbr
,b.snz_sex_gender_code
,b.snz_deceased_year_nbr
,b.snz_deceased_month_nbr
,b.snz_birth_date_proxy
,DATEDIFF(YEAR, b.snz_birth_date_proxy, '$(refdate)') AS age 
,'3999-12-31' AS dod 
,'ID' AS [type]
 INTO #id_ad
 FROM #id AS a
      INNER JOIN [$(idicleanversion)].[data].[personal_detail] AS b ON a.snz_uid = b.snz_uid
     WHERE a.snz_uid NOT IN (SELECT DISTINCT snz_uid FROM [$(idicleanversion)].[dia_clean].[deaths])
     AND a.snz_uid NOT IN (SELECT DISTINCT snz_uid FROM #id_dd)
     AND a.snz_uid NOT IN (SELECT DISTINCT snz_uid FROM #id_od);

 /* join all tables together*/

DROP TABLE IF EXISTS #id_final;
WITH id_union AS (
SELECT
* 
FROM #id_dd
UNION ALL
SELECT * FROM #id_od
UNION ALL
SELECT * FROM #id_ad
)

SELECT
* 
,DATEDIFF(YEAR, snz_birth_date_proxy, dod) AS age_at_death
,CASE WHEN age IS NOT NULL THEN 0 ELSE 1 END AS death_status
INTO #id_final
FROM id_union;

/* select all required variables */

DROP TABLE IF EXISTS #id_min;
SELECT 
snz_uid
,[type]
,entity
,source_table
,min_date
,snz_sex_gender_code
,snz_birth_month_nbr
,snz_birth_year_nbr
,snz_birth_date_proxy
,age
,death_status
,snz_deceased_year_nbr
,snz_deceased_month_nbr
,CASE WHEN dod = '3999-12-31' THEN NULL ELSE dod END AS dod
,CASE WHEN age_at_death > 1000 THEN NULL ELSE age_at_death END AS age_at_death
INTO #id_min
FROM #id_final;

/*take earliest recorded date for each snz_uid and create table */
DROP TABLE IF EXISTS #id_dbl;
SELECT 
snz_uid
,[type]
,entity
,source_table
,min_date
,snz_sex_gender_code
,snz_birth_month_nbr
,snz_birth_year_nbr
,snz_birth_date_proxy
,age
,death_status
,snz_deceased_year_nbr
,snz_deceased_month_nbr
,dod
,age_at_death
INTO #id_dbl
FROM #id_min a
WHERE min_date = (
SELECT MIN(min_date)
FROM #id_min b
WHERE b.snz_uid = a.snz_uid)
ORDER BY snz_uid;

/* remove duplicate snz_uid with the same minimum date but different entities or sources. Create table in IDI_Sandpit */

DROP TABLE IF EXISTS [$(targetdb)].[$(targetschema)].[$(projprefix)_intellectual_disability];

WITH cte AS 
(SELECT ROW_NUMBER() OVER(PARTITION BY snz_uid
ORDER BY snz_uid DESC) AS rn
FROM #id_dbl)
DELETE FROM cte WHERE rn > 1;

SELECT 
snz_uid
,[type]
,entity
,source_table
,min_date
,snz_sex_gender_code
,snz_birth_month_nbr
,snz_birth_year_nbr
,snz_birth_date_proxy
,age
,death_status
,snz_deceased_year_nbr
,snz_deceased_month_nbr
,dod
,age_at_death

INTO [$(targetdb)].[$(targetschema)].[$(projprefix)_intellectual_disability]

FROM #id_dbl