-- Based on the SQL script from "Z:\SHARE\DSS\IDR Data Requests\DataRequestsProcess\commonScripts\sql\zipcodes9.sql"
SELECT
    ALL_PATIENTS.PATNT_KEY AS 'Patient Key'
    ,PATNT_ENCNTR_KEY_XREF1.ENCNTR_CSN_ID AS 'Encounter # (CSN)'
    ,PATIENT_ENCOUNTER_DTL.ENCNTR_EFF_DATE AS 'Encounter Effective Date'
    ,COALESCE(ALL_ADDRESSES.CLEANED_ZIP_CD,ALL_ADDRESSES.ZIP_CD) AS '9-Digit Zip Code'
    ,COALESCE(dbo.ZIP_CODE_MAPPER_XREF.ZIP_CD, ALL_PT_SNAPSHOTS_ENCOUNTER.PATNT_ZIP_CD) AS 'Zip Code'
FROM
    dbo.ALL_PATIENTS 
    RIGHT OUTER JOIN dbo.ALL_PATIENT_SNAPSHOTS  ALL_PT_SNAPSHOTS_ENCOUNTER ON (ALL_PT_SNAPSHOTS_ENCOUNTER.PATNT_KEY=dbo.ALL_PATIENTS.PATNT_KEY)
    RIGHT OUTER JOIN dbo.PATIENT_ENCOUNTER_DTL ON (ALL_PT_SNAPSHOTS_ENCOUNTER.PATNT_SNAPSHT_KEY=dbo.PATIENT_ENCOUNTER_DTL.DSCHRG_PATNT_SNAPSHT_KEY  AND  dbo.PATIENT_ENCOUNTER_DTL.TEST_IND='N')
    LEFT OUTER JOIN dbo.PATNT_ENCNTR_KEY_XREF  PATNT_ENCNTR_KEY_XREF1 ON (dbo.PATIENT_ENCOUNTER_DTL.PATNT_ENCNTR_KEY=PATNT_ENCNTR_KEY_XREF1.PATNT_ENCNTR_KEY  AND  dbo.PATIENT_ENCOUNTER_DTL.TEST_IND='N')
    LEFT OUTER JOIN dbo.ALL_LOCATIONS  ALL_LOCATIONS3 ON (ALL_PT_SNAPSHOTS_ENCOUNTER.PATNT_LOCATN_KEY=ALL_LOCATIONS3.LOCATN_KEY)
    LEFT OUTER JOIN dbo.ZIP_CODE_MAPPER_XREF ON (ALL_LOCATIONS3.ZIP5_CD=dbo.ZIP_CODE_MAPPER_XREF.ZIP_CD)
    LEFT OUTER JOIN dbo.ALL_ADDRESSES ON (ALL_PT_SNAPSHOTS_ENCOUNTER.ADDR_KEY=ALL_ADDRESSES.ADDR_KEY)
WHERE
   ALL_PATIENTS.PATNT_KEY in ( {PYTHON_VARIABLE: Patient Key} )
   AND
   PATIENT_ENCOUNTER_DTL.ENCNTR_EFF_DATE BETWEEN {PYTHON_VARIABLE: Encounter Effective Date Start} AND {PYTHON_VARIABLE: Encounter Effective Date End}
   AND
   ( dbo.ALL_PATIENTS.TEST_IND='N'  )
ORDER BY
    [Patient Key]
    ,[Encounter Effective Date]
    ,[Encounter # (CSN)]