- गनियारी, जिला - बिलासपुर
+ ART CLIENT HAND HELD CARD
-
-
- दिनाँक
-
-
:
-
{{patient.registrationDate | bahmniDate}}
-
-
-
- रजिस्ट्रेशन
-
-
:
-
{{patient.primaryIdentifier.identifier}}
-
-
-
- नाम
-
-
:
-
- {{patient.fullNameLocal()}}
-
-
-
-
- उम्र
-
-
:
-
{{patient.age | age}}
-
-
-
- लिंग
-
-
:
-
{{patient.gender}}
-
-
-
- पिता/पति
-
-
:
-
{{patient.primaryRelative}}
-
-
-
- गाँव
-
-
:
-
{{patient.address.cityVillage}}
-
-
-
- तहसील
-
-
:
-
{{patient.address.address3}}
-
+
+
+ Facility Name :
+
+
.....................
+
+
+
+ Full Names:
+
+
+ {{patient.fullNameLocal()}}
+
+
+
+
+ Age: {{patient.age | age}}
+
+
+ Sex: {{patient.gender}}
+
+
+
+
+
+
+ ART No: {{patient.primaryIdentifier.identifier}}
+
+
+ HEI No: .............
+
+
+
+
+ ART Start Date:
+
+
+ .... / .... / ....
+
+
+
+
+
Initial ART Regimen:
+
+
+ .......................
+
+
-
+
+
+
+
Carry this card and present it to the health worker at every visit.
+
Keep the appointment date as indicated in this card.
+
In case of new symptoms, visit the facility or call health worker.
+
If you can't come, call health worker on number below.
+
+
Health Facility Telephone No. ......................
+
+
+
-
-
-
+
+
+
+
diff --git a/openmrs/apps/reports/facilityReports.json b/openmrs/apps/reports/facilityReports.json
new file mode 100644
index 000000000..c7c2d9f15
--- /dev/null
+++ b/openmrs/apps/reports/facilityReports.json
@@ -0,0 +1,30 @@
+{
+ "missedAppointmentReport": {
+ "name": "Missed Appointment Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/missedAppointments.sql"
+ }
+ },
+ "summaryAppointmentReport": {
+ "name": "Appointment Summary Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/summaryAppointmentReport.sql"
+ }
+ },
+ "visitAppointmentReport": {
+ "name": "Visit Appointment Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/visitAppointmentReport.sql"
+ }
+ },
+ "walkinAppointmentReport": {
+ "name": "WalkIn Visit Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/walkinAppointmentReport.sql"
+ }
+ }
+}
diff --git a/openmrs/apps/reports/monthlyReports.json b/openmrs/apps/reports/monthlyReports.json
new file mode 100644
index 000000000..76b82f5af
--- /dev/null
+++ b/openmrs/apps/reports/monthlyReports.json
@@ -0,0 +1,269 @@
+{
+ "artRegisterReport": {
+ "name": "ART Register",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/artRegister.sql"
+ }
+ },
+ "artDispensingReport": {
+ "name": "ART Dispensing Register",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/artDispensingRegister.sql"
+ }
+ },
+ "artMonthlyStartedOnArtReport": {
+ "name": "ART Monthly report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/artMonthlyStartedOnArtReport.sql"
+ }
+ },
+ "artMonthlyViralLoadReport": {
+ "name": "ART Monthly Report Viral Load",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "ART Monthly Report Viral Load",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ART_Monthly_Report_Viral_Load.sql"
+ }
+ }
+ ]
+ }
+ },
+ "htsMonthlyReport": {
+ "name": "HTS Monthly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/HTS_Monthly_Report.sql"
+ }
+ },
+ "currentOnArt": {
+ "name": "ART Monthly Report - Current On ART",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "ARV regimen at end of Last Month",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/currentOnArtLastMonth.sql"
+ }
+ },
+ {
+ "name": "Clients who received ART this reporting period by Regimen",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/currentOnARTThisMonth.sql"
+ }
+ }
+ ]
+ }
+ },
+ "indexTestingReport": {
+ "name": "Master Contact Listing Report",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "Master Contact Listing Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/indextesting_masterindex.sql"
+ }
+ },
+ {
+ "name": "Contacts Not Tested Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/contactsNotTested.sql"
+ }
+ },
+ {
+ "name": "Contacts Tested Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/contactsTested.sql"
+ }
+ }
+ ]
+ }
+ },
+ "ancMonthlyReport": {
+ "name": "ANC PMTCT Register",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "ANC PMTCT Register",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/anc_pmtct_register.sql"
+ }
+ },
+ {
+ "name": "ANC PMTCT REGISTER CONTINUATION",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/AncPmtctReportTabOne.sql"
+ }
+ },
+ {
+ "name": "ANC PMTCT REGISTER CONTINUATION",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/AncPmtctReportTabSecond.sql"
+ }
+ },
+ {
+ "name": "ANC PMTCT Discharge Information",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ancpmtctDischargeTab.sql"
+ }
+ }
+ ]
+ }
+ },
+ "highViralloadReport": {
+ "name": "High Viral Load Register",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/highViralloadReport.sql"
+ }
+ },
+ "hivExposedInfants": {
+ "name": "HIV Exposed Infant Monthly Report",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "HIV Exposed Infant Monthly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/HIV_Exposed_Infant_Monthly_Report.sql"
+ }
+ }
+ ]
+ }
+ },
+ "PMTCTAllreports": {
+ "name": "PMTCT Monthly Report",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "PMTCT ANC visits Syphilis and HBV Testing",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_ANC_visits_Syphilis_and_HBV_Testing.sql"
+ }
+ },
+ {
+ "name": "PMTCT Clients who received ART",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Clients_who_received_ART.sql"
+ }
+ },
+ {
+ "name": "ANC Partner Index Contact Counselling",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ANC_Partner_Index_Contact_Counselling.sql"
+ }
+ },
+ {
+ "name": "PMTCT Counseling and Testing Maternity",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_Maternity.sql"
+ }
+ },
+ {
+ "name": "PMTCT Counseling and Testing ANC Clinic",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_ANC_Clinic.sql"
+ }
+ }
+ ]
+ }
+ },
+ "ArtCohortAnalysisForm": {
+ "name": "ART Cohort Analysis Form",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ArtCohortAnalysisForm.sql"
+ }
+ },
+ "Maternity": {
+ "name": "Maternity PMTCT Register",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/maternitypmtct.sql"
+ }
+ },
+ "hivExposedInfantRegisterReport": {
+ "name": "Exposed Infant Register",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "Exposed Infant Register Page 1",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabFirst.sql"
+ }
+ },
+ {
+ "name": "Exposed Infant Register Page 2",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabSecond.sql"
+ }
+ },
+ {
+ "name": "Follow up Visits - Page 1",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/hivExposedInfantRegisterTabThird.sql"
+ }
+ },
+ {
+ "name": "Follow Up Visits - Page 2",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/hivExposedInfantRegisterForthTab.sql"
+ }
+ },
+ {
+ "name": "Confirmatory HIV Rapid Test",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/hivExposedInfantRegisterTabFive.sql"
+ }
+ }
+ ]
+ }
+ },
+ "dhisSampleReportTest": {
+ "name": "Dhis Sample Report",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "High Viral Load Patients",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/dhisSampleRepportTest.sql"
+ }
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/openmrs/apps/reports/quarterlyReports.json b/openmrs/apps/reports/quarterlyReports.json
new file mode 100644
index 000000000..47a7c1f3e
--- /dev/null
+++ b/openmrs/apps/reports/quarterlyReports.json
@@ -0,0 +1,101 @@
+{
+ "missedAppointmentReport": {
+ "name": "HTS - Quarterly report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_report.sql"
+ }
+ },
+ "index_sheet_quarterly": {
+ "name": "Index Sheet - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_index_sheet.sql"
+ }
+ },
+ "art_quarterly": {
+ "name": "ART Treatment - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_art.sql"
+ }
+ },
+ "pmtct_stat_quarterly": {
+ "name": "PMTCT STAT - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_pmtct_anc.sql"
+ }
+ },
+ "pmtct_art_quarterly": {
+ "name": "PMTCT ART - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_pmtct_art.sql"
+ }
+ },
+ "pmtct_eid_quarterly": {
+ "name": "PMTCT EID - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_pmtct_eid.sql"
+ }
+ },
+ "pmtct_hei_pos_quarterly": {
+ "name": "PMTCT HEI POS - Quarterly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quarterly_pmtct_hei_pos.sql"
+ }
+ },
+ "tb_art_datacollectiontool_quartely": {
+ "name": "TB ART Data Collection Tool - Quartely Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/tbARTdatacollectiontool.sql"
+ }
+ },
+ "pmtct_quartely_report": {
+ "name": "PMTCT FO- Quartely Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/pmtct_fo_quarterly_report.sql"
+ }
+ },
+ "viral_load_report": {
+ "name": "Viral Load - Quartely Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quartely_viral_load_report.sql"
+ }
+ },
+ "tx_ml_quartely_report": {
+ "name": "TX ML - Quartely Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/quartely_tx_ml.sql"
+ }
+ },
+ "tx_tb_and_tb_prev": {
+ "name": "TX TB and TB PREV - Quartely Report",
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "Newly started on ART",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_newly_started.sql"
+ }
+ },
+ {
+ "name": "Previously on ART",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_previously_started_on_art.sql"
+ }
+ }
+ ]
+ }
+ }
+}
diff --git a/openmrs/apps/reports/reports.json b/openmrs/apps/reports/reports.json
index 056c565d6..1918d5fbf 100644
--- a/openmrs/apps/reports/reports.json
+++ b/openmrs/apps/reports/reports.json
@@ -26,635 +26,152 @@
]
}
},
- "testReport": {
- "name": "Test Observation Report",
- "type": "observations",
- "config": {
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "visitAttributes": [
- "Visit Status",
- "Admission Status"
- ],
- "showVisitInfo": true,
- "showProvider": true,
- "conceptNamesToFilter": [
- ],
- "conceptNameDisplayFormat": "shortNamePreferred",
- "conceptValuesToFilter": ["0..20","100..","True"],
- "conceptClassesToFilter": [],
- "locationTagsToFilter": [],
- "programsToFilter": [],
- "applyDateRangeFor": "obsDate",
- "encounterPerRow": true,
- "forDataAnalysis": true,
- "visitTypesToFilter": [
- "PHARMACY VISIT",
- "OPD"
- ]
- }
- },
- "testFormReport":{
- "name": "Test Forms Report",
- "type": "forms",
- "config": {
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "visitAttributes": [
- "Visit Status",
- "Admission Status"
- ],
- "showVisitInfo": true,
- "showProvider": true,
- "formNamesToFilter": ["Vitals"],
- "conceptNameDisplayFormat": "shortNamePreferred",
- "locationTagsToFilter": [],
- "programsToFilter": [],
- "applyDateRangeFor": "obsDate",
- "visitTypesToFilter": []
- }
- },
- "formBuilderReport":{
- "name": "Form builder form Report",
- "type": "formBuilder",
- "config": {
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "visitAttributes": [
- "Visit Status"
- ],
- "showVisitInfo": true,
- "showProvider": true,
- "formNamesToFilter": [ "Test Form"],
- "conceptNameDisplayFormat": "shortNamePreferred",
- "locationTagsToFilter": [],
- "programsToFilter": [],
- "applyDateRangeFor": "obsDate",
- "visitTypesToFilter": []
- }
- },
- "chiefComplaintReport": {
- "name": "Chief Complaint Report",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Chief Complaint"
- ],
- "countOnlyClosedVisits": "false",
- "visitTypes": [
- "IPD",
- "OPD"
- ]
- }
- },
- "inpatientMorbidity": {
- "name": "Inpatient Morbidity",
- "type": "diagnosisCount",
- "config": {
- "visitTypes": [
- "IPD"
- ]
- }
- },
- "outpatientMorbidity": {
- "name": "Outpatient Morbidity",
- "type": "diagnosisCount",
- "config": {
- "visitTypes": [
- "OPD"
- ]
- }
- },
- "laboratoryServices": {
- "name": "Laboratory Services",
- "type": "TestCount"
- },
- "genericLaboratoryServices": {
- "name": "Generic Laboratory Services",
- "type": "ElisGeneric",
- "config": {
- "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/testCount.sql"
- }
- },
- "bloodPressure": {
- "name": "Blood Pressure",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Systolic",
- "Diastolic"
- ],
- "countOnlyClosedVisits": "false",
- "countOncePerPatient": "false",
- "visitTypes": [
- "OPD",
- "IPD"
- ]
- }
- },
- "smokingHistoryReport": {
- "name": "Smoking History Report",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Smoking History"
- ],
- "countOnlyClosedVisits": "false",
- "countOncePerPatient": "true"
- }
- },
- "vitalsTemplateReport": {
- "name": "Vitals Template Report",
- "type": "obsTemplate",
- "config": {
- "templateName": "Vitals",
- "patientAttributes": [
- "caste",
- "education"
- ],
- "applyDateRangeFor": "encounterCreateDate"
- }
- },
- "tuberculosisIntakeTemplateReport": {
- "name": "Tuberculosis Intake Template Report",
- "type": "obsTemplate",
- "config": {
- "templateName": "Tuberculosis Intake Template"
- }
- },
- "diabetes": {
- "name": "Diabetes",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Diabetes Intake"
- ],
- "visitTypes": [
- "OPD",
- "IPD"
- ]
- }
- },
- "codedValueRangeBasedReport": {
- "name": "Coded Value Range Based Report",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Diabetes, Cormorbidities"
- ],
- "countOncePerPatient": "true"
- }
- },
- "OPD/IPDVisitCount": {
- "name": "OPD/IPD Visit Count",
- "type": "IpdOpdVisitCount"
- },
- "haemoglobinRangeBasedReport": {
- "name": "Haemoglobin Range Based Report",
- "type": "NumericConceptValuesCount",
- "config": {
- "rangeGroupName": "Haemoglobin",
- "ageGroupName": "Haemoglobin",
- "conceptNames": [
- "Haemoglobin"
- ],
- "countOncePerPatient": "false"
- }
- },
- "radiology(X-Ray)Count": {
- "name": "Radiology(X-Ray) Count",
- "type": "ObsCountByConceptClass",
- "config": {
- "conceptClassNames": [
- "Radiology"
- ]
- }
- },
- "obsValuesCountsForAlbuminMCHOperationDateAndPosture(bloodPressure)": {
- "name": "Obs Values Counts for Albumin, MCH, Operation Date and Posture(blood pressure)",
- "type": "ObsValueCount",
- "config": {
- "conceptNames": [
- "Albumin",
- "MCH",
- "Date of Operation",
- "Posture"
- ]
- }
- },
- "tuberculosisTreatmentCompletionDates": {
- "name": "Tuberculosis Treatment Completion dates",
- "type": "DateConceptValuesPatientsList",
- "config": {
- "conceptNames": [
- "Tuberculosis, Treatment Completion Date"
- ],
- "templateName": "Tuberculosis Outcome Template"
- }
- },
- "patientsListWithAlbuminMCHAndHIVELISA(Blood)TestsResults": {
- "name": "Patients list with Albumin, MCH and HIV ELISA (Blood) tests results",
- "type": "PatientsWithLabtestResults",
- "config": {
- "conceptNames": [
- "HIV ELISA (Blood)",
- "Albumin",
- "MCH"
- ],
- "testOutcome": [
- "abnormal",
- "normal"
- ]
- }
- },
- "IPDPatientsReport": {
- "name": "IPD Patients Report",
- "type": "ipdPatients",
- "config": {
- "addressAttributes": [
- "address1",
- "city_village"
- ],
- "patientAttributes": [
- "caste",
- "education"
- ],
- "conceptNames": [
- "Height",
- "Weight"
- ],
- "filterBy": "Date of Discharge"
- }
- },
- "nutritionProgramNutritionalStatusOfRegisteredChildren": {
- "name": "Nutrition Program - Nutritional status of registered children",
- "type": "obsCount",
- "config": {
- "ageGroupName": "All Ages",
- "conceptNames": [
- "Nutrition, Nutritional Status"
- ],
- "countOncePerPatient": "true",
- "countOnlyClosedVisits": "false"
- }
- },
- "patientsProgramStateCountReport": {
- "name": "Patients Program State Count Report",
- "type": "programStateCount",
- "config": {
- "programName": "Malaria Program"
- }
- },
- "programPatientStateReport": {
- "name": "Program Patient State Report",
- "type": "PatientProgramReport",
- "config": {
- "programName": "Malaria Program"
- }
- },
- "programStateTransitionReport": {
- "name": "Program State Transition Report",
- "type": "programStateTransitionReport",
- "config": {
- "programName": "Malaria Program"
- }
- },
- "OrderFulfillmentReport": {
- "name": "Order Fulfillment Report",
- "type": "OrderFulfillmentReport",
- "config": {
- "type": "OrderFulfillmentReport",
- "orderTypes": [
- "Order",
- "Drug Order"
- ]
- }
- },
- "visitReport": {
- "name": "Visit Report",
- "type": "visitReport",
- "config": {
- "personAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "visitAttributes": [
- "Visit Status"
- ]
- }
- },
"patientReport": {
"name": "Patient Information",
"type": "PatientReport"
},
- "obsCannedReport": {
- "name": "Obs Canned Report",
- "type": "obsCannedReport",
- "config": {
- "patientAttributes": [
- "caste",
- "education"
- ],
- "applyDateRangeFor": "ObsRecording",
- "addressAttributes": [
- "postal_code",
- "city_village"
- ],
- "conceptNames": [
- "Pulse",
- "WEIGHT",
- "Vitals, Systolic",
- "Temperature"
- ],
- "visitIndependentConcept": [
- "HEIGHT",
- "Temperature"
- ],
- "enrolledProgram": "HIV Program",
- "showObsOnlyForProgramDuration": false
- }
- },
- "drugOrderReport": {
- "name": "Drug Order report",
- "type": "DrugOrder"
- },
- "SampleGenericProgramReport": {
- "name": "Generic program sample report",
- "type": "programs",
- "config": {
- "patientAttributes": [
- "education",
- "primaryContact",
- "secondaryContact",
- "class",
- "cluster"
- ],
- "patientAddresses": [
- "city_village",
- "address3"
- ],
- "programAttributes": [],
- "forDataAnalysis": true,
- "showAllStates": true,
- "programNamesToFilter": [
- "HIV Program"
- ]
- }
- },
- "pivotReport": {
- "name": "Blood Pressure",
- "type": "aggregation",
- "config": {
- "report":{
- "type": "observations",
- "config": {
- "conceptNamesToFilter":["Diastolic Data", "Systolic Data"],
- "showVisitInfo" : true,
- "forDataAnalysis": true,
- "visitAttributes": ["Visit Status", "Admission Status"],
- "visitTypesToFilter": ["IPD"]
-
- }
- },
- "rowGroups": [
- "Gender"
- ],
- "columnGroups": [
- "Concept Name", "value"
- ],
- "distinctGroups": [
- "Patient Identifier"
- ]
- }
- },
- "pivotReportOfVisits": {
- "name": "Aggregation report for visits",
- "type": "aggregation",
- "config": {
- "report":{
- "type": "visits",
- "config": {
- "forDataAnalysis": true,
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "visitAttributes": [
- "Visit Status",
- "Admission Status"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "applyDateRangeFor": "visitStopDate",
- "visitTypesToFilter": [
- "PHARMACY VISIT",
- "OPD"
- ]
- }
- },
- "rowGroups": [
- "Gender"
- ],
- "columnGroups": [
- "Visit Status"
- ],
- "distinctGroups": [
- "Patient Identifier"
- ]
- }
- },
- "pivotReportForPrograms": {
- "name": "HIV Program Pivot Report",
- "type": "aggregation",
- "config": {
- "report": {
- "type": "programs",
- "config": {
- "patientAttributes": [
- ],
- "patientAddresses": [
- "city_village",
- "address3"
- ],
- "programAttributes": [],
- "forDataAnalysis": true,
- "showAllStates": true,
- "programNamesToFilter": [
- "TB Program",
- "HIV Program"
- ]
- }
- },
- "columnGroups": [
- "Program name"
- ],
- "rowGroups": [
- "Gender"
- ],
- "distinctGroups": [
- "Patient Identifier"
- ],
- "showTotalRow":true,
- "showTotalColumn":true
-
- }
- },
- "concatenatedReport": {
- "name": "ConcatenatedReport",
- "type": "concatenated",
- "config": {
- "reports": [
- {
- "name": "Visit Report",
- "type": "visits",
- "config": {
- "forDataAnalysis": true,
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "visitAttributes": [
- "Visit Status",
- "Admission Status"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "applyDateRangeFor": "visitStopDate",
- "visitTypesToFilter": [
- "PHARMACY VISIT",
- "OPD"
- ]
- }
- },
- {
- "name": "Obs Canned Report",
- "type": "obsCannedReport",
- "config": {
- "patientAttributes": [
- "caste",
- "education"
- ],
- "applyDateRangeFor": "ObsRecording",
- "addressAttributes": [
- "postal_code",
- "city_village"
- ],
- "conceptNames": [
- "Pulse",
- "WEIGHT",
- "Vitals, Systolic",
- "Temperature"
- ],
- "visitIndependentConcept": [
- "HEIGHT",
- "Temperature"
- ],
- "enrolledProgram": "HIV Program",
- "showObsOnlyForProgramDuration": false
- }
- }
- ]
- }
- },
- "GenericLabOrderReport": {
- "name": "Lab Order Results",
- "type": "labOrders",
- "config": {
- "patientAttributes": [
- "caste",
- "class",
- "education",
- "occupation",
- "primaryContact"
- ],
- "patientAddresses": [
- "address3",
- "city_village"
- ],
- "visitAttributes": [
- "Visit Status"
- ],
- "showVisitInfo": true,
- "showProvider": true,
- "programsToFilter": [],
- "showReferredOutTests": true,
- "conceptNamesToFilter": [
- "Haemoglobin (Blood)"
- ],
- "conceptValuesToFilter": [
- "10..100"
- ],
- "forDataAnalysis": true,
- "excludeColumns": [
- "address3"
- ],
- "showOrderDateTime": true
- }
- },
- "GenericLabOrderReportAggregation": {
- "name": "Test Name vs Gender",
- "type": "aggregation",
- "config": {
- "report": {
- "type": "labOrders",
- "config": {
- "forDataAnalysis": true,
- "showVisitInfo": true
- }
- },
- "rowGroups": [
- "Test Name"
- ],
- "columnGroups": [
- "Gender"
- ],
- "distinctGroups": [
- "Patient Identifier"
- ]
- }
- }
+ "Dhis Sample Report": {
+ "name": "Dhis Sample Report",
+ "DHISProgram": true,
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "Dhis Sample Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/Dhis_Sample_Report.sql"
+ }
+ }
+ ]
+ }
+ },
+ "HIV Exposed Infant Monthly Report": {
+ "name": "HIV Exposed Infant Monthly Report",
+ "DHISProgram": true,
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "HIV Exposed Infant Monthly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/HIV_Exposed_Infant_Monthly_Report.sql"
+ }
+ }
+ ]
+ }
+ },
+ "ART Monthly Report Viral Load": {
+ "name": "ART Monthly Report Viral Load",
+ "DHISProgram": true,
+ "type": "concatenated",
+ "config": {
+ "reports": [
+ {
+ "name": "ART Monthly Report Viral Load",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ART_Monthly_Report_Viral_Load.sql"
+ }
+ }
+ ]
+ }
+ },
+ "PMTCT ANC visits Syphilis and HBV Testing": {
+ "name": "PMTCT ANC visits Syphilis and HBV Testing",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "PMTCT ANC visits Syphilis and HBV Testing",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_ANC_visits_Syphilis_and_HBV_Testing.sql"
+ }
+ }
+ ]
+ }
+ },
+ "PMTCT Counseling and Testing Maternity": {
+ "name": "PMTCT Counseling and Testing Maternity",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "PMTCT Counseling and Testing Maternity",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_Maternity.sql"
+ }
+ }
+ ]
+ }
+ },
+ "HTS Monthly Report": {
+ "name": "HTS Monthly Report",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "HTS Monthly Report",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/HTS_Monthly_Report.sql"
+ }
+ }
+ ]
+ }
+ },
+ "PMTCT Counseling and Testing ANC Clinic": {
+ "name": "PMTCT Counseling and Testing ANC Clinic",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "PMTCT Counseling and Testing ANC Clinic",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_ANC_Clinic.sql"
+ }
+ }
+ ]
+ }
+ },
+ "PMTCT Clients who received ART": {
+ "name": "PMTCT Clients who received ART",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "PMTCT Clients who received ART",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/PMTCT_Clients_who_received_ART.sql"
+ }
+ }
+ ]
+ }
+ },
+ "ANC Partner Index Contact Counselling": {
+ "name": "ANC Partner Index Contact Counselling",
+ "type": "concatenated",
+ "DHISProgram": true,
+ "config": {
+ "reports": [
+ {
+ "name": "ANC Partner Index Contact Counselling",
+ "type": "MRSGeneric",
+ "config": {
+ "sqlPath": "/var/www/bahmni_config/openmrs/apps/reports/sql/ANC_Partner_Index_Contact_Counselling.sql"
+ }
+ }
+ ]
+ }
+ }
}
diff --git a/openmrs/apps/reports/sql/ANC_Partner_Index_Contact_Counselling.sql b/openmrs/apps/reports/sql/ANC_Partner_Index_Contact_Counselling.sql
new file mode 100644
index 000000000..a31b12a2a
--- /dev/null
+++ b/openmrs/apps/reports/sql/ANC_Partner_Index_Contact_Counselling.sql
@@ -0,0 +1,585 @@
+-- ANC Partner Index contact HIV Counseling and testing
+
+SELECT
+ 'Couples Pre-test counseled jointly' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+select
+'Partners who had HIV testing' as 'Title',
+count(distinct(case when pidd is not null and sexual_partner_age is null and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Unknown age',
+count(distinct(case when pidd is not null and sexual_partner_age >= 10 and sexual_partner_age < 15 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '10 - 14 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 15 and sexual_partner_age < 20 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '15 - 19 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 20 and sexual_partner_age < 25 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '20 - 24 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 25 and sexual_partner_age < 30 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '25 - 29 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 30 and sexual_partner_age < 35 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '30 - 34 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 35 and sexual_partner_age < 40 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '35 - 39 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 40 and sexual_partner_age < 45 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '40 - 44 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 45 and sexual_partner_age < 50 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '45 - 49 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 50 and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as '50+ YRS',
+count(distinct(case when pidd is not null and partnerResult in ('Positive','Negative') and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Total'
+from (
+select pidd, (case when hiv_result is null and hts_result is null then 'N/A' else case when hiv_result is not null and hts_result is not null then hts_result else case when hiv_result is not null and hts_result is null
+then hiv_result else case when hiv_result is null and hts_result is not null then hts_result end end end end) as 'partnerResult' ,sexual_partner_age, sexual_partner_sex from (
+select person_id as pidd, spouse, obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'spouse', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = (
+select concept_id from concept_name where name = 'Spouse' and concept_name_type = 'FULLY_SPECIFIED') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(obs_group_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.obs_group_id = c.maxdate
+)tIsSpouse
+left join (
+select person_id, (select name from concept_name where concept_id = HivKnownStatus and concept_name_type = 'SHORT') as 'hiv_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'HivKnownStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResult on tIsSpouse.obs_group_id = tSpouseHivResult.obs_group_id
+left join (
+select person_id, (select name from concept_name where concept_id = NewTestedResult and concept_name_type = 'SHORT') as 'hts_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'NewTestedResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResultAfterTesting on tIsSpouse.obs_group_id = tSpouseHivResultAfterTesting.obs_group_id
+left join (
+select person_id, gender, birthdate ,(TIMESTAMPDIFF(YEAR, birthdate, '#endDate#')) as 'Age'from person
+)tDemographics on tIsSpouse.pidd = tDemographics.person_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tIsSpouse.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(select name from concept_name where concept_id = value_coded and concept_name_type = 'FULLY_SPECIFIED') as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tIsSpouse.obs_group_id = tSexualPartnerGender.obs_group_id
+)p
+
+UNION ALL
+
+select
+'Partners testing HIV positive' as 'Title',
+count(distinct(case when pidd is not null and sexual_partner_age is null and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Unknown age',
+count(distinct(case when pidd is not null and sexual_partner_age >= 10 and sexual_partner_age < 15 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '10 - 14 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 15 and sexual_partner_age < 20 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '15 - 19 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 20 and sexual_partner_age < 25 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '20 - 24 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 25 and sexual_partner_age < 30 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '25 - 29 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 30 and sexual_partner_age < 35 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '30 - 34 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 35 and sexual_partner_age < 40 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '35 - 39 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 40 and sexual_partner_age < 45 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '40 - 44 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 45 and sexual_partner_age < 50 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '45 - 49 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 50 and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as '50+ YRS',
+count(distinct(case when pidd is not null and partnerResult = 'Positive' and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Total'
+from (
+select pidd, (case when hiv_result is null and hts_result is null then 'N/A' else case when hiv_result is not null and hts_result is not null then hts_result else case when hiv_result is not null and hts_result is null
+then hiv_result else case when hiv_result is null and hts_result is not null then hts_result end end end end) as 'partnerResult' ,sexual_partner_age, sexual_partner_sex from (
+select person_id as pidd, spouse, obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'spouse', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = (
+select concept_id from concept_name where name = 'Spouse' and concept_name_type = 'FULLY_SPECIFIED') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(obs_group_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.obs_group_id = c.maxdate
+)tIsSpouse
+left join (
+select person_id, (select name from concept_name where concept_id = HivKnownStatus and concept_name_type = 'SHORT') as 'hiv_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'HivKnownStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResult on tIsSpouse.obs_group_id = tSpouseHivResult.obs_group_id
+left join (
+select person_id, (select name from concept_name where concept_id = NewTestedResult and concept_name_type = 'SHORT') as 'hts_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'NewTestedResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResultAfterTesting on tIsSpouse.obs_group_id = tSpouseHivResultAfterTesting.obs_group_id
+left join (
+select person_id, gender, birthdate ,(TIMESTAMPDIFF(YEAR, birthdate, '#endDate#')) as 'Age'from person
+)tDemographics on tIsSpouse.pidd = tDemographics.person_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tIsSpouse.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(select name from concept_name where concept_id = value_coded and concept_name_type = 'FULLY_SPECIFIED') as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tIsSpouse.obs_group_id = tSexualPartnerGender.obs_group_id
+)p
+
+UNION ALL
+
+select
+'Partners with discordant results' as 'Title',
+count(distinct(case when pidd is not null and sexual_partner_age is null and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Unknown age',
+count(distinct(case when pidd is not null and sexual_partner_age >= 10 and sexual_partner_age < 15 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '10 - 14 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 15 and sexual_partner_age < 20 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '15 - 19 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 20 and sexual_partner_age < 25 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '20 - 24 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 25 and sexual_partner_age < 30 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '25 - 29 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 30 and sexual_partner_age < 35 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '30 - 34 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 35 and sexual_partner_age < 40 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '35 - 39 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 40 and sexual_partner_age < 45 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '40 - 44 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 45 and sexual_partner_age < 50 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '45 - 49 YRS',
+count(distinct(case when pidd is not null and sexual_partner_age >= 50 and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as '50+ YRS',
+count(distinct(case when pidd is not null and partnerResult = 'Negative' and sexual_partner_sex in ('Male','Female') then pidd end)) as 'Total'
+from (
+select pidd, (case when hiv_result is null and hts_result is null then 'N/A' else case when hiv_result is not null and hts_result is not null then hts_result else case when hiv_result is not null and hts_result is null
+then hiv_result else case when hiv_result is null and hts_result is not null then hts_result end end end end) as 'partnerResult' ,sexual_partner_age, sexual_partner_sex from (
+select person_id as pidd, spouse, obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'spouse', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = (
+select concept_id from concept_name where name = 'Spouse' and concept_name_type = 'FULLY_SPECIFIED') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(obs_group_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.obs_group_id = c.maxdate
+)tIsSpouse
+left join (
+select person_id, (select name from concept_name where concept_id = HivKnownStatus and concept_name_type = 'SHORT') as 'hiv_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'HivKnownStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResult on tIsSpouse.obs_group_id = tSpouseHivResult.obs_group_id
+left join (
+select person_id, (select name from concept_name where concept_id = NewTestedResult and concept_name_type = 'SHORT') as 'hts_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'NewTestedResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResultAfterTesting on tIsSpouse.obs_group_id = tSpouseHivResultAfterTesting.obs_group_id
+left join (
+select person_id, gender, birthdate ,(TIMESTAMPDIFF(YEAR, birthdate, '#endDate#')) as 'Age'from person
+)tDemographics on tIsSpouse.pidd = tDemographics.person_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tIsSpouse.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(select name from concept_name where concept_id = value_coded and concept_name_type = 'FULLY_SPECIFIED') as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tIsSpouse.obs_group_id = tSexualPartnerGender.obs_group_id
+)p
+
+UNION ALL
+
+ select
+'Index Case Contact Tested' as 'Title',
+count(distinct(case when Names is not null and ContactsAge is null and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as 'Unknown age',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '10 - 14 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '15 - 19 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '20 - 24 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '25 - 29 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '30 - 34 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '35 - 39 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '40 - 44 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '45 - 49 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as '50+ YRS',
+count(distinct(case when Names is not null and ContactsAge >= 10 and wasContactTested = 'YES' and PatnerGender in ('M','F') then Names end)) as 'Total'
+
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b
+
+UNION ALL
+
+select
+'Index Case contacts positive'as'Title',
+count(distinct(case when Names is not null and ContactsAge is null and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as 'Unknown age',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '10 - 14 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '15 - 19 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '20 - 24 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '25 - 29 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '30 - 34 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '35 - 39 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '40 - 44 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '45 - 49 YRS',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as '50+ YRS',
+count(distinct(case when Names is not null and ContactsAge >= 10 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('M','F') then Names end)) as 'Total'
+
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/ART_Monthly_Report_Viral_Load.sql b/openmrs/apps/reports/sql/ART_Monthly_Report_Viral_Load.sql
new file mode 100644
index 000000000..9933d9e37
--- /dev/null
+++ b/openmrs/apps/reports/sql/ART_Monthly_Report_Viral_Load.sql
@@ -0,0 +1,979 @@
+-- ART Monthly Report - Viral Load
+
+SELECT
+ '<1 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE())< 1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '1-4 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '5-9 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '10-14 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '15-19 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '20-24 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '25-29 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '30-34 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '35-39 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '40-44 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '45-49 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '50-54 YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '55+ YRS' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Total' as 'Age Group',
+ count(maleGenderSampleCollected) as 'Sample Collected\n Male',
+ count(femaleGenderSampleCollected) as 'Sample Collected\n Female',
+ count(pregnantWomensSampleCollected) as 'Sample Collected\n Pregnant',
+ count(breastFeedingWomensSampleCollected) as 'Sample Collected\n Breastfeeding',
+ count(totalSampleCollected) as 'Sample Collected\n Total',
+ count(maleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Male',
+ count(femaleGenderResultCollected999) as 'Results Received\n <1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected999) as 'Results Received\n <1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected999) as 'Results Received\n <1000 copies/ml \n Total',
+ count(maleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Male',
+ count(femaleGenderResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Female',
+ count(pregnantWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Pregnant',
+ count(breastFeedingWomensResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Breastfeeding',
+ count(totalResultCollected1000) as 'Results Received\n >=1000 copies/ml \n Total',
+ count(maleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Male',
+ count(femaleGenderResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Female',
+ count(pregnantWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Pregnant',
+ count(breastFeedingWomensResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Breastfeeding',
+ count(totalResultCollected11000) as 'Clients with high VL\n (>=1000copies/ml) Traced \n Total'
+FROM (
+ SELECT
+ CASE WHEN (gender = 'M' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END maleGenderSampleCollected,
+ CASE WHEN (gender = 'F' and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END femaleGenderSampleCollected,
+ CASE WHEN (gender = 'F' and pregnant=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END pregnantWomensSampleCollected,
+ CASE WHEN (gender = 'F' and breastFeeding=1 and MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomensSampleCollected,
+ CASE WHEN (MONTH(viralSampleDate) = MONTH(CURDATE()) AND YEAR(viralSampleDate) = YEAR(CURDATE())) THEN 1 END totalSampleCollected,
+ CASE WHEN (gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END maleGenderResultCollected999,
+ CASE WHEN (gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END femaleGenderResultCollected999,
+ CASE WHEN (gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END pregnantWomensResultCollected999,
+ CASE WHEN (gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END breastFeedingWomensResultCollected999,
+ CASE WHEN (MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult < 1000) THEN 1 END totalResultCollected999,
+ CASE WHEN (gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected1000,
+ CASE WHEN (gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected1000,
+ CASE WHEN (gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected1000,
+ CASE WHEN (gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected1000,
+ CASE WHEN (MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected1000,
+ CASE WHEN (gender = 'M' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END maleGenderResultCollected11000,
+ CASE WHEN (gender = 'F' and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END femaleGenderResultCollected11000,
+ CASE WHEN (gender = 'F' and pregnant=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END pregnantWomensResultCollected11000,
+ CASE WHEN (gender = 'F' and breastFeeding=1 and MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END breastFeedingWomensResultCollected11000,
+ CASE WHEN (MONTH(vlResultDate) = MONTH(CURDATE()) AND YEAR(vlResultDate) = YEAR(CURDATE()) and vlResult >= 1000) THEN 1 END totalResultCollected11000
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'viralSampleDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date VL Sample Collected?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vl ON (vl.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'vlResultDate', o.value_numeric AS 'vlResult' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="VL Results" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p;
diff --git a/openmrs/apps/reports/sql/AncPmtctReportTabOne.sql b/openmrs/apps/reports/sql/AncPmtctReportTabOne.sql
new file mode 100644
index 000000000..5b5b6a0f6
--- /dev/null
+++ b/openmrs/apps/reports/sql/AncPmtctReportTabOne.sql
@@ -0,0 +1,203 @@
+select concat(coalesce(given_name,''),' ', coalesce(middle_name,'') ,' ',coalesce(family_name,'') ) as 'Full Names', concat('Follow up status: ',"\n",' -----------',"\n",'TB Status :') as 'Month of Starting PMTCT' ,
+concat(cd4month0,"\n",'------',"\n",weightMonth0) as '0',
+concat(cd4month1,"\n",'------',"\n",weightMonth1) as '1', concat(cd4month2,"\n",'------',"\n",weightMonth2) as '2',
+concat('Follow up status:wt(kg)',"\n",'----------',"\n",'TB Status: CD4/Vl') as 'Month',
+concat(cd4month3,"\n",'------',"\n",weightMonth3) as '3',
+concat(cd4month4,"\n",'------',"\n",weightMonth4) as '4', concat(cd4month5,"\n",'------',"\n",weightMonth5) as '5',
+concat(cd4month6,"\n",'------',"\n",weightMonth6) as '6',concat(cd4month7,"\n",'------',"\n",weightMonth7) as '7',
+concat(cd4month8,"\n",'------',"\n",weightMonth8) as '8',concat(cd4month9,"\n",'------',"\n",weightMonth9) as '9',
+concat(cd4month10,"\n",'------',"\n",weightMonth10) as '10',concat(cd4month11,"\n",'------',"\n",weightMonth11) as '11',
+concat(cd4month12,"\n",'------',"\n",weightMonth12) as '12',concat(cd4month13,"\n",'------',"\n",weightMonth13) as '13',
+concat(cd4month14,"\n",'------',"\n",weightMonth14) as '14',concat(cd4month15,"\n",'------',"\n",weightMonth15) as '15'
+ from (
+select given_name, middle_name,family_name, tpersonDemographics.personid, cd4month0,cd4month1,cd4month2,cd4month3,cd4month4 ,cd4month5 ,cd4month6 ,cd4month7 ,cd4month8,cd4month9,cd4month10,cd4month11,cd4month12,
+cd4month13 ,cd4month14 ,cd4month15 from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created between '#startDate#' and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tpersonDemographics
+left join(
+select person_id,
+(case when date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then value_numeric else 0 end) as 'cd4month0'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') group by person_id
+)tcd4month0 on tpersonDemographics.personid = tcd4month0.person_id
+left join(
+select person_id, value_numeric as 'cd4month1'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 1 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 1 MONTH) group by person_id
+ )tttcd4month1 on tpersonDemographics.personid= tttcd4month1.person_id
+ left join(
+select person_id, value_numeric as 'cd4month2'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 2 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 2 MONTH) group by person_id
+ )tttcd4month2 on tpersonDemographics.personid= tttcd4month2.person_id
+ left join(
+select person_id, value_numeric as 'cd4month3'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 3 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 3 MONTH) group by person_id
+ )tttcd4month3 on tpersonDemographics.personid= tttcd4month3.person_id
+left join (
+select person_id, value_numeric as 'cd4month4'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 4 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 4 MONTH) group by person_id
+)ttcd4month4 on tpersonDemographics.personid= ttcd4month4.person_id
+left join (
+select person_id, value_numeric as 'cd4month5'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 5 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 5 MONTH) group by person_id
+)ttcd4month5 on tpersonDemographics.personid= ttcd4month5.person_id
+left join (
+select person_id, value_numeric as 'cd4month6'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 6 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 6 MONTH) group by person_id
+)ttcd4month6 on tpersonDemographics.personid= ttcd4month6.person_id
+left join (
+select person_id, value_numeric as 'cd4month7'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 7 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 7 MONTH) group by person_id
+)ttcd4month7 on tpersonDemographics.personid= ttcd4month7.person_id
+left join (
+select person_id, value_numeric as 'cd4month8'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 8 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 8 MONTH) group by person_id
+)ttcd4month8 on tpersonDemographics.personid= ttcd4month8.person_id
+left join (
+select person_id, value_numeric as 'cd4month9'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 9 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 9 MONTH) group by person_id
+)ttcd4month9 on tpersonDemographics.personid= ttcd4month9.person_id
+left join (
+select person_id, value_numeric as 'cd4month10'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 10 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 10 MONTH) group by person_id
+)ttcd4month10 on tpersonDemographics.personid= ttcd4month10.person_id
+left join (
+select person_id, value_numeric as 'cd4month11'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 11 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 11 MONTH) group by person_id
+)ttcd4month11 on tpersonDemographics.personid= ttcd4month11.person_id
+left join (
+select person_id, value_numeric as 'cd4month12'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 12 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 12 MONTH) group by person_id
+)ttcd4month12 on tpersonDemographics.personid= ttcd4month12.person_id
+left join (
+select person_id, value_numeric as 'cd4month13'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 13 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 13 MONTH) group by person_id
+)ttcd4month13 on tpersonDemographics.personid= ttcd4month13.person_id
+left join (
+select person_id, value_numeric as 'cd4month14'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 14 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 14 MONTH) group by person_id
+)ttcd4month14 on tpersonDemographics.personid= ttcd4month14.person_id
+left join (
+select person_id, value_numeric as 'cd4month15'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 15 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 15 MONTH) group by person_id
+)ttcd4month15 on tpersonDemographics.personid= ttcd4month15.person_id
+)tcd4
+left join (
+select * from (
+select tPersonDemographicscd415.personid , weightMonth0,weightMonth1,weightMonth2,weightMonth3,weightMonth4 ,weightMonth5 ,weightMonth6 ,weightMonth7 ,weightMonth8,weightMonth9,weightMonth10,weightMonth11,weightMonth12,
+weightMonth13 ,weightMonth14 ,weightMonth15 from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created between '#startDate#' and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPersonDemographicscd415
+left join(
+select person_id,
+(case when date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then value_numeric else 0 end) as 'weightMonth0'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') group by person_id
+)tweight0 on tPersonDemographicscd415.personid = tweight0.person_id
+left join (
+select person_id, value_numeric as 'weightMonth1'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 1 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 1 MONTH) group by person_id
+)ttweight1 on tPersonDemographicscd415.personid = ttweight1.person_id
+left join (
+select person_id, value_numeric as 'weightMonth2'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 2 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 2 MONTH) group by person_id
+)ttweight2 on tPersonDemographicscd415.personid = ttweight2.person_id
+left join (
+select person_id, value_numeric as 'weightMonth3'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 3 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 3 MONTH) group by person_id
+)ttweight3 on tPersonDemographicscd415.personid = ttweight3.person_id
+left join(
+select person_id, value_numeric as 'weightMonth4'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 4 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 4 MONTH) group by person_id
+)ttweight4 on tPersonDemographicscd415.personid = ttweight4.person_id
+left join (
+select person_id, value_numeric as 'weightMonth5'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 5 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 5 MONTH) group by person_id
+)ttweight5 on tPersonDemographicscd415.personid = ttweight5.person_id
+left join (
+select person_id, value_numeric as 'weightMonth6'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 6 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 6 MONTH) group by person_id
+)ttweight6 on tPersonDemographicscd415.personid = ttweight6.person_id
+left join (
+select person_id, value_numeric as 'weightMonth7'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 7 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 7 MONTH) group by person_id
+)ttweight7 on tPersonDemographicscd415.personid = ttweight7.person_id
+left join (
+select person_id, value_numeric as 'weightMonth8'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 8 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 8 MONTH) group by person_id
+)ttweight8 on tPersonDemographicscd415.personid = ttweight8.person_id
+left join (
+select person_id, value_numeric as 'weightMonth9'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 9 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 9 MONTH) group by person_id
+)ttweight9 on tPersonDemographicscd415.personid = ttweight9.person_id
+left join (
+select person_id, value_numeric as 'weightMonth10'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 10 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 10 MONTH) group by person_id
+)ttweight10 on tPersonDemographicscd415.personid = ttweight10.person_id
+left join (
+select person_id, value_numeric as 'weightMonth11'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 11 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 11 MONTH) group by person_id
+)ttweight11 on tPersonDemographicscd415.personid = ttweight11.person_id
+left join (
+select person_id, value_numeric as 'weightMonth12'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 12 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 12 MONTH) group by person_id
+)ttweight12 on tPersonDemographicscd415.personid = ttweight12.person_id
+left join (
+select person_id, value_numeric as 'weightMonth13'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 13 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 13 MONTH) group by person_id
+)ttweight13 on tPersonDemographicscd415.personid = ttweight13.person_id
+left join (
+select person_id, value_numeric as 'weightMonth14'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 14 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 14 MONTH) group by person_id
+)ttweight14 on tPersonDemographicscd415.personid = ttweight14.person_id
+left join (
+select person_id, value_numeric as 'weightMonth15'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 15 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 15 MONTH) group by person_id
+)ttweight15 on tPersonDemographicscd415.personid = ttweight15.person_id
+)t15weight
+)tcd4weight15 on tcd4.personid = tcd4weight15.personid
diff --git a/openmrs/apps/reports/sql/AncPmtctReportTabSecond.sql b/openmrs/apps/reports/sql/AncPmtctReportTabSecond.sql
new file mode 100644
index 000000000..42a4db7c3
--- /dev/null
+++ b/openmrs/apps/reports/sql/AncPmtctReportTabSecond.sql
@@ -0,0 +1,286 @@
+select concat(coalesce(given_name,''),' ', coalesce(middle_name,'') ,' ',coalesce(family_name,'') ) as 'Full Names',
+concat('(Follow up status) wt(kg)',"\n",'------------',"\n",'(TB Status) CD4/Vl') as 'Month of Starting PMTCT',
+concat(cd4month16,"\n",'------',"\n",weightMonth16) as '16', concat(cd4month17,"\n",'------',"\n",weightMonth17) as '17',
+concat(cd4month18,"\n",'------',"\n",weightMonth18) as '18',
+concat(cd4month19,"\n",'------',"\n",weightMonth19) as '19', concat(cd4month20,"\n",'------',"\n",weightMonth20) as '20',
+concat(cd4month21,"\n",'------',"\n",weightMonth21) as '21',concat(cd4month22,"\n",'------',"\n",weightMonth22) as '22',
+concat(cd4month23,"\n",'------',"\n",weightMonth23) as '23',concat(cd4month24,"\n",'------',"\n",weightMonth24) as '24',
+concat(cd4month25,"\n",'------',"\n",weightMonth25) as '25',concat(cd4month26,"\n",'------',"\n",weightMonth26) as '26',
+concat(cd4month27,"\n",'------',"\n",weightMonth27) as '27',concat(cd4month28,"\n",'------',"\n",weightMonth28) as '28',
+concat(cd4month29,"\n",'------',"\n",weightMonth29) as '29',concat(cd4month30,"\n",'------',"\n",weightMonth30) as '30',
+concat(cd4month31,"\n",'------',"\n",weightMonth31) as '31',concat(cd4month32,"\n",'------',"\n",weightMonth32) as '32',
+concat(cd4month33,"\n",'------',"\n",weightMonth33) as '33',concat(cd4month34,"\n",'------',"\n",weightMonth34) as '34',
+concat(cd4month35,"\n",'------',"\n",weightMonth35) as '35',concat(cd4month36,"\n",'------',"\n",weightMonth36) as '36',
+concat(cd4month37,"\n",'------',"\n",weightMonth37) as '37',concat(cd4month38,"\n",'------',"\n",weightMonth38) as '38'
+ from (
+select given_name, middle_name,family_name, tpersonDemographics.personid, cd4month0,cd4month16,cd4month17,cd4month18 ,cd4month19 ,cd4month20 ,cd4month21 ,cd4month22,cd4month23,cd4month24,cd4month25,cd4month26,
+cd4month27 ,cd4month28 ,cd4month29 , cd4month30 ,cd4month31 ,cd4month32, cd4month33 ,cd4month34 ,cd4month35 ,cd4month36 ,cd4month37 , cd4month38 from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created between '#startDate#' and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tpersonDemographics
+left join(
+select person_id,
+(case when date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then value_numeric else 0 end) as 'cd4month0'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') group by person_id
+)tcd4month0 on tpersonDemographics.personid = tcd4month0.person_id
+left join(
+select person_id, value_numeric as 'cd4month16'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 16 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 16 MONTH) group by person_id
+ )tttcd4month16 on tpersonDemographics.personid= tttcd4month16.person_id
+ left join(
+select person_id, value_numeric as 'cd4month17'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 17 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 17 MONTH) group by person_id
+ )tttcd4month17 on tpersonDemographics.personid= tttcd4month17.person_id
+ left join(
+select person_id, value_numeric as 'cd4month18'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 18 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 18 MONTH) group by person_id
+ )tttcd4month18 on tpersonDemographics.personid= tttcd4month18.person_id
+left join (
+select person_id, value_numeric as 'cd4month19'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 19 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 19 MONTH) group by person_id
+)ttcd4month19 on tpersonDemographics.personid= ttcd4month19.person_id
+left join (
+select person_id, value_numeric as 'cd4month20'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 20 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 20 MONTH) group by person_id
+)ttcd4month20 on tpersonDemographics.personid= ttcd4month20.person_id
+left join (
+select person_id, value_numeric as 'cd4month21'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 21 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 21 MONTH) group by person_id
+)ttcd4month21 on tpersonDemographics.personid= ttcd4month21.person_id
+left join (
+select person_id, value_numeric as 'cd4month22'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 22 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 22 MONTH) group by person_id
+)ttcd4month22 on tpersonDemographics.personid= ttcd4month22.person_id
+left join (
+select person_id, value_numeric as 'cd4month23'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 23 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 23 MONTH) group by person_id
+)ttcd4month23 on tpersonDemographics.personid= ttcd4month23.person_id
+left join (
+select person_id, value_numeric as 'cd4month24'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 24 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 24 MONTH) group by person_id
+)ttcd4month24 on tpersonDemographics.personid= ttcd4month24.person_id
+left join (
+select person_id, value_numeric as 'cd4month25'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 25 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 25 MONTH) group by person_id
+)ttcd4month25 on tpersonDemographics.personid= ttcd4month25.person_id
+left join (
+select person_id, value_numeric as 'cd4month26'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 26 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 26 MONTH) group by person_id
+)ttcd4month26 on tpersonDemographics.personid= ttcd4month26.person_id
+left join (
+select person_id, value_numeric as 'cd4month27'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 27 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 27 MONTH) group by person_id
+)ttcd4month27 on tpersonDemographics.personid= ttcd4month27.person_id
+left join (
+select person_id, value_numeric as 'cd4month28'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 28 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 28 MONTH) group by person_id
+)ttcd4month28 on tpersonDemographics.personid= ttcd4month28.person_id
+left join (
+select person_id, value_numeric as 'cd4month29'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 29 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 29 MONTH) group by person_id
+)ttcd4month29 on tpersonDemographics.personid= ttcd4month29.person_id
+left join (
+select person_id, value_numeric as 'cd4month30'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 30 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 30 MONTH) group by person_id
+)ttcd4month30 on tpersonDemographics.personid= ttcd4month30.person_id
+left join (
+select person_id, value_numeric as 'cd4month31'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 31 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 31 MONTH) group by person_id
+)ttcd4month31 on tpersonDemographics.personid= ttcd4month31.person_id
+left join (
+select person_id, value_numeric as 'cd4month32'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 32 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 32 MONTH) group by person_id
+)ttcd4month32 on tpersonDemographics.personid= ttcd4month32.person_id
+left join (
+select person_id, value_numeric as 'cd4month33'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 33 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 33 MONTH) group by person_id
+)ttcd4month33 on tpersonDemographics.personid= ttcd4month33.person_id
+left join (
+select person_id, value_numeric as 'cd4month34'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 34 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 34 MONTH) group by person_id
+)ttcd4month34 on tpersonDemographics.personid= ttcd4month34.person_id
+left join (
+select person_id, value_numeric as 'cd4month35'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 35 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 35 MONTH) group by person_id
+)ttcd4month35 on tpersonDemographics.personid= ttcd4month35.person_id
+left join (
+select person_id, value_numeric as 'cd4month36'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 36 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 36 MONTH) group by person_id
+)ttcd4month36 on tpersonDemographics.personid= ttcd4month36.person_id
+left join (
+select person_id, value_numeric as 'cd4month37'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 37 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 37 MONTH) group by person_id
+)ttcd4month37 on tpersonDemographics.personid= ttcd4month37.person_id
+left join (
+select person_id, value_numeric as 'cd4month38'
+from obs where concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 38 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 38 MONTH) group by person_id
+)ttcd4month38 on tpersonDemographics.personid= ttcd4month38.person_id
+)tcd4
+left join (
+select * from (
+select tPersonDemographicscd415.personid , weightMonth0,weightMonth16,weightMonth17,weightMonth18 ,weightMonth19 ,weightMonth20 ,weightMonth21 ,weightMonth22,weightMonth23,weightMonth24,weightMonth25,weightMonth26,
+weightMonth27 ,weightMonth28 ,weightMonth29,weightMonth30 ,weightMonth31 ,weightMonth32,weightMonth33 ,weightMonth34 ,weightMonth35,weightMonth36 ,weightMonth37 ,weightMonth38 from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created between '#startDate#' and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPersonDemographicscd415
+left join(
+select person_id,
+(case when date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then value_numeric else 0 end) as 'weightMonth0'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') group by person_id
+)tweight0 on tPersonDemographicscd415.personid = tweight0.person_id
+left join (
+select person_id, value_numeric as 'weightMonth16'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 16 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 16 MONTH) group by person_id
+)ttweight16 on tPersonDemographicscd415.personid = ttweight16.person_id
+left join (
+select person_id, value_numeric as 'weightMonth17'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 17 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 17 MONTH) group by person_id
+)ttweight17 on tPersonDemographicscd415.personid = ttweight17.person_id
+left join (
+select person_id, value_numeric as 'weightMonth18'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 18 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 18 MONTH) group by person_id
+)ttweight18 on tPersonDemographicscd415.personid = ttweight18.person_id
+left join(
+select person_id, value_numeric as 'weightMonth19'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 19 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 19 MONTH) group by person_id
+)ttweight19 on tPersonDemographicscd415.personid = ttweight19.person_id
+left join (
+select person_id, value_numeric as 'weightMonth20'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 20 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 20 MONTH) group by person_id
+)ttweight20 on tPersonDemographicscd415.personid = ttweight20.person_id
+left join (
+select person_id, value_numeric as 'weightMonth21'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 21 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 21 MONTH) group by person_id
+)ttweight21 on tPersonDemographicscd415.personid = ttweight21.person_id
+left join (
+select person_id, value_numeric as 'weightMonth22'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 22 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 22 MONTH) group by person_id
+)ttweight22 on tPersonDemographicscd415.personid = ttweight22.person_id
+left join (
+select person_id, value_numeric as 'weightMonth23'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 23 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 23 MONTH) group by person_id
+)ttweight23 on tPersonDemographicscd415.personid = ttweight23.person_id
+left join (
+select person_id, value_numeric as 'weightMonth24'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 24 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 24 MONTH) group by person_id
+)ttweight24 on tPersonDemographicscd415.personid = ttweight24.person_id
+left join (
+select person_id, value_numeric as 'weightMonth25'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 25 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 25 MONTH) group by person_id
+)ttweight25 on tPersonDemographicscd415.personid = ttweight25.person_id
+left join (
+select person_id, value_numeric as 'weightMonth26'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 26 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 26 MONTH) group by person_id
+)ttweight26 on tPersonDemographicscd415.personid = ttweight26.person_id
+left join (
+select person_id, value_numeric as 'weightMonth27'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 27 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 27 MONTH) group by person_id
+)ttweight27 on tPersonDemographicscd415.personid = ttweight27.person_id
+left join (
+select person_id, value_numeric as 'weightMonth28'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 28 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 28 MONTH) group by person_id
+)ttweight28 on tPersonDemographicscd415.personid = ttweight28.person_id
+left join (
+select person_id, value_numeric as 'weightMonth29'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 29 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 29 MONTH) group by person_id
+)ttweight29 on tPersonDemographicscd415.personid = ttweight29.person_id
+left join (
+select person_id, value_numeric as 'weightMonth30'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 30 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 30 MONTH) group by person_id
+)ttweight30 on tPersonDemographicscd415.personid = ttweight30.person_id
+left join (
+select person_id, value_numeric as 'weightMonth31'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 31 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 31 MONTH) group by person_id
+)ttweight31 on tPersonDemographicscd415.personid = ttweight31.person_id
+left join (
+select person_id, value_numeric as 'weightMonth32'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 32 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 32 MONTH) group by person_id
+)ttweight32 on tPersonDemographicscd415.personid = ttweight32.person_id
+left join (
+select person_id, value_numeric as 'weightMonth33'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 33 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 33 MONTH) group by person_id
+)ttweight33 on tPersonDemographicscd415.personid = ttweight33.person_id
+left join (
+select person_id, value_numeric as 'weightMonth34'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 34 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 34 MONTH) group by person_id
+)ttweight34 on tPersonDemographicscd415.personid = ttweight34.person_id
+left join (
+select person_id, value_numeric as 'weightMonth35'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 35 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 35 MONTH) group by person_id
+)ttweight35 on tPersonDemographicscd415.personid = ttweight35.person_id
+left join (
+select person_id, value_numeric as 'weightMonth36'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 36 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 36 MONTH) group by person_id
+)ttweight36 on tPersonDemographicscd415.personid = ttweight36.person_id
+left join (
+select person_id, value_numeric as 'weightMonth37'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 37 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 37 MONTH) group by person_id
+)ttweight37 on tPersonDemographicscd415.personid = ttweight37.person_id
+left join (
+select person_id, value_numeric as 'weightMonth38'
+from obs where concept_id = (select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified') and date_created between DATE_ADD(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 38 MONTH) and
+ DATE_ADD(DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59'), INTERVAL 38 MONTH) group by person_id
+)ttweight38 on tPersonDemographicscd415.personid = ttweight38.person_id
+)t15weight
+)tcd4weight15 on tcd4.personid = tcd4weight15.personid
diff --git a/openmrs/apps/reports/sql/ArtCohortAnalysisForm.sql b/openmrs/apps/reports/sql/ArtCohortAnalysisForm.sql
new file mode 100644
index 000000000..e494f6694
--- /dev/null
+++ b/openmrs/apps/reports/sql/ArtCohortAnalysisForm.sql
@@ -0,0 +1,499 @@
+
+select 'Started ART In this Clinic (original Cohort)',
+(case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value not in (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select 'Transfer in',
+(case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value = (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select 'Transfer out',
+(case when value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select patient_id , obs.value_datetime
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join concept_name cn on o.concept_id = cn.concept_id
+left join obs obs on o.patient_id = obs.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738')
+and obs.concept_id = (select concept_id from concept_name where name = 'Transferred Out Date' and concept_name_type = 'FULLY_SPECIFIED'
+and obs.status = 'FINAL') group by o.patient_id
+)tTransferOut
+union all
+select 'Net Current Cohort', CEIL(@initial1 + @tranferIn1 - @transferOut1) as 'start' , CEIL(@initial2 + @tranferIn2 - @transferOut2) as '6mo' , CEIL(@initial3 + @tranferIn3 - @transferOut3) as '12mo'
+,CEIL(@initial4 + @tranferIn4 - @transferOut4) as '24mo', CEIL(@initial5 + @tranferIn5 - @transferOut5) as '36mo', CEIL(@initial6 + @tranferIn6 - @transferOut6) as '48mo'
+,CEIL(@initial7 + @tranferIn7 - @transferOut7) as '60mo'
+from (
+select
+@initial1 := (case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@initial2 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@initial3 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@initial4 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@initial5 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@initial6 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@initial7 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value not in (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select
+@tranferIn1 := (case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@tranferIn2 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@tranferIn3 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@tranferIn4 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@tranferIn5 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@tranferIn6 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@tranferIn7 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value = (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select
+@transferOut1 := (case when value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@transferOut2 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@transferOut3 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@transferOut4 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@transferOut5 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@transferOut6 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@transferOut7 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select patient_id , obs.value_datetime
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join concept_name cn on o.concept_id = cn.concept_id
+left join obs obs on o.patient_id = obs.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738')
+and obs.concept_id = (select concept_id from concept_name where name = 'Transferred Out Date' and concept_name_type = 'FULLY_SPECIFIED'
+and obs.status = 'FINAL') group by o.patient_id
+)tTransferOut
+) tNetCohort limit 1
+union all
+select 'On Original 1st Line Regimen',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) = 1) pp
+union all
+select 'On Alternate 1st Line Regimen (Substituted)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 1) tAltenateFirstLine
+union all
+select 'On 2nd Line Regimen (Switched)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tSecondSubstitutedLine
+union all
+select 'Stopped',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'Interruption type' and concept_name_type = 'Fully_specified')
+and ob.value_coded = (select concept_id from concept_name where name = 'Stop' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tRegimenStopped
+union all
+select 'Died',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'Fully_specified')
+and ob.value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0 ) tPatientDied
+union all
+select 'Lost to Follow-up (DROP)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'Fully_specified')
+and ob.value_coded = (select concept_id from concept_name where name = 'Lost Follow Up(< 28days)' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tLostToFollowup
+union all
+select 'Alive and on ART (E+F+G)',sum(start) as 'start' , sum(6mo) as '6mo' , sum(12mo) as '12mo' , sum(24mo) as '24mo' , sum(36mo) as '36mo' , sum(48mo) as '48mo' , sum(60mo) as '60mo' from (
+select 'On Original 1st Line Regimen',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) = 1) pp
+union all
+select 'On Alternate 1st Line Regimen (Substituted)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 1) tAltenateFirstLine
+union all
+select 'On 2nd Line Regimen (Switched)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tSecondSubstitutedLine
+)tefg
+union all
+select 'Percent of cohort alive and on ART[K / D * 100 ]', CEIL(@perc1) as 'start', CEIL(@perc2) as '6mo' , CEIL(@perc3) as '12mo' ,CEIL(@perc4) as '24mo' , CEIL(@perc5) as '36mo', CEIL(@perc6) as '48mo', CEIL(@perc7) as '60mo' from (
+select @perc1 := CEIL((@original1+@alternate1+@switched1) / (@initial1 + @tranferIn1 - @transferOut1) * 100) as 'start', @perc2 := CEIL((@original2+@alternate2+@switched2) / (@initial2 + @tranferIn2 - @transferOut2) * 100) as '6mo',@perc3 := CEIL((@original3+@alternate3+@switched3) / (@initial3 + @tranferIn3 - @transferOut3) * 100) as '12mo',
+@perc4 := CEIL((@original4+@alternate4+@switched4)/(@initial4 + @tranferIn4 - @transferOut4) * 100) as '24mo',
+@perc5 := CEIL((@original5+@alternate5+@switched5) / (@initial5 + @tranferIn5 - @transferOut5) * 100) as '36mo',@perc6 := CEIL((@original6+@alternate6+@switched6) / (@initial2 + @tranferIn2 - @transferOut2) * 100) as '48mo', @perc7 := CEIL((@original7+@alternate7+@switched7) /(@initial2 + @tranferIn2 - @transferOut2) * 100)as '60mo'from (
+select 'On Original 1st Line Regimen',
+@original1 := (case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@original2 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@original3 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@original4 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@original5 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@original6 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@original7 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) = 1) pp
+union all
+select 'On Alternate 1st Line Regimen (Substituted)',
+@alternate1 := (case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@alternate1 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 1) tAltenateFirstLine
+union all
+select 'On 2nd Line Regimen (Switched)',
+@switched1 := (case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@switched2 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@switched3 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@switched4 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@switched5 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@switched6 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@switched7 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+where cn.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG') and cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'Fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tSecondSubstitutedLine
+)tefg limit 1
+union all
+select
+@initial1 := (case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@initial2 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@initial3 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@initial4 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@initial5 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@initial6 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@initial7 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value not in (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select
+@tranferIn1 := (case when startdate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@tranferIn2 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@tranferIn3 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@tranferIn4 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@tranferIn5 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@tranferIn6 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@tranferIn7 := SUM(CASE WHEN startdate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from
+(
+select distinct(o.patient_id) , min(o.date_created) as 'startdate',o.concept_id , dr.dosage_form , pa.person_id from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join person_attribute pa on o.patient_id = pa.person_id
+left join person p on pa.person_id = p.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738') and pa.person_attribute_type_id = 33 and
+pa.value = (SELECT concept_id FROM openmrs.concept_name where name = 'Transfer-in' and concept_name_type = 'FULLY_SPECIFIED')
+group by o.patient_id ) patients
+union all
+select
+@transferOut1 := (case when value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@transferOut2 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@transferOut3 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@transferOut4 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@transferOut5 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@transferOut6 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@transferOut7 := SUM(CASE WHEN value_datetime between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select patient_id , obs.value_datetime
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join concept_name cn on o.concept_id = cn.concept_id
+left join obs obs on o.patient_id = obs.person_id
+where dr.dosage_form = (select concept_id from concept_name where uuid = '95955de4-7440-4482-88f6-e5daefc2d738')
+and obs.concept_id = (select concept_id from concept_name where name = 'Transferred Out Date' and concept_name_type = 'FULLY_SPECIFIED'
+and obs.status = 'FINAL') group by o.patient_id
+)tTransferOutlimit limit 1
+) hh
+union all
+select 'Fraction CD4 <200 (of adults with available CD4 at baseline)', CEIL(@baselineStart / @baseStart ) as 'start', CEIL(@baseline6 / @base6) as '6mo', CEIL(@baseline12 / @base12 ) as '12mo', CEIL(@baseline24 / @base24 ) as '24mo', CEIL(@baseline36 / @base36 ) as '36mo',
+CEIL(@baseline48 / @base48 ) as '48mo', CEIL(@baseline60 / @base60 ) as '60mo' from (
+select 'Fraction CD4 <200 (of adults with available CD4 at baseline)',
+@baselineStart := (case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@baseline6 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@baseline12 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@baseline24 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@baseline36 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@baseline48 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@baseline60 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+left join person pa on ob.person_id = pa.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'Fully_specified')
+and ob.value_numeric < 200 and TIMESTAMPDIFF(YEAR,pa.birthdate,NOW()) >= 18
+group by o.patient_id having count(o.patient_id) > 0) tb2
+union all
+select 'Fraction CD4 <200 (of adults with available CD4 at baseline)',
+@baseStart := (case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+@base6 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+@base12 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+@base24 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+@base36 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+@base48 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+@base60 := SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+left join person pa on ob.person_id = pa.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'CD4' and concept_name_type = 'Fully_specified')
+and ob.value_numeric > 0 and TIMESTAMPDIFF(YEAR,pa.birthdate,NOW()) >= 18
+group by o.patient_id having count(o.patient_id) > 0) tb1
+)tcd4lessthan200 LIMIT 1
+union all
+select 'Done Viral Load (VL)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+ from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'Fully_specified')
+and ob.value_numeric > 0
+group by o.patient_id having count(o.patient_id) > 0) tDoneViralload
+union all
+select 'Viral Load < 1000 copies /ml',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'Fully_specified')
+and ob.value_numeric < 1000
+group by o.patient_id having count(o.patient_id) > 0) tVllessthanthousand
+union all
+select 'Presumptive TB (Pr TB)',
+(case when mindate between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then count(distinct(patient_id)) else 0 end) as 'start',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 6 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '6mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 12 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '12mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 24 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '24mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 36 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '36mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 48 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '48mo',
+SUM(CASE WHEN mindate between DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 60 MONTH),'%Y-%m-%d 23:59:59')) then 1 else 0 end) as '60mo'
+from (
+select o.patient_id, o.concept_id , dr.dosage_form , min(o.date_created) as 'mindate' from orders o
+left join drug dr on o.concept_id = dr.concept_id
+inner join concept_name cn on o.concept_id = cn.concept_id
+left join obs ob on o.patient_id = ob.person_id
+where cn.concept_name_type = 'Fully_specified' and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen'
+and concept_name_type = 'Fully_specified')
+and ob.concept_id = (select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'Fully_specified')
+and ob.value_coded = (select concept_id from concept_name where name = 'True' and concept_name_type =
+'fully_specified')
+group by o.patient_id having count(o.patient_id) > 0) tPresumptiveTb
+union all
+select 'Currently on TB treatment (TBRx)',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#','%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#'),'%Y-%m-%d 23:59:59') then person_id end)) as 'start',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 6 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 6 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '6mo',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 12 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 12 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '12mo',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 24 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 24 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '24mo',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 36 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 36 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '36mo',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 48 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 48 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '48mo',
+count(distinct(case when person_id is not null and obs_datetime > DATE_FORMAT('#startDate#' - INTERVAL 60 MONTH ,'%Y-%m-01') and obs_datetime <= DATE_FORMAT(LAST_DAY('#startDate#') - INTERVAL 60 MONTH,'%Y-%m-%d 23:59:59') then person_id end)) as '60mo'
+from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dataStartedTBrx', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+
+
diff --git a/openmrs/apps/reports/sql/Dhis_Sample_Report.sql b/openmrs/apps/reports/sql/Dhis_Sample_Report.sql
new file mode 100644
index 000000000..ccddb7b8e
--- /dev/null
+++ b/openmrs/apps/reports/sql/Dhis_Sample_Report.sql
@@ -0,0 +1,10 @@
+select count(person_id) as 'Number Of Patients' from (
+select (SELECT @a:= 0) AS a , obs_datetime as 'registrationDate', person_id , vlresults from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'vlresults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate and vlresults >= 1000
+)tHighVlPatients
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/HIV_Exposed_Infant_Monthly_Report.sql b/openmrs/apps/reports/sql/HIV_Exposed_Infant_Monthly_Report.sql
new file mode 100644
index 000000000..4917b7c0a
--- /dev/null
+++ b/openmrs/apps/reports/sql/HIV_Exposed_Infant_Monthly_Report.sql
@@ -0,0 +1,852 @@
+-- HIV-exposed Infants Monthly Report
+select 'Number of New HIV-Exposed Infants enrolled',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+from (
+select person_id , dateStartedProphylaxis from (
+select person_id, (SELECT @a:= 0) AS a , concept_id, value_datetime as 'dateStartedProphylaxis' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and value_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateStartedProphylaxis
+inner join (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff('#endDate#',p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name = 'HeiRelationship' and concept_name_type = 'FULLY_SPECIFIED')
+and (datediff('#endDate#',p.birthdate) / 365) < 2
+)tDemogrpahics on tDateStartedProphylaxis.person_id = tDemogrpahics.pid
+inner join (
+select person_id, isEnrolled from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isEnrolled', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsEnrolled on tDemogrpahics.pid = tIsEnrolled.person_id
+
+
+UNION ALL
+
+
+select 'Number Of HIV-Exposed Infants seen (New And Old)',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+from (
+select person_id , dateStartedProphylaxis from (
+select person_id, (SELECT @a:= 0) AS a , concept_id, value_datetime as 'dateStartedProphylaxis' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and value_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateStartedProphylaxis
+inner join (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff('#endDate#',p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and (datediff('#endDate#',p.birthdate) / 365) < 2
+)tDemogrpahics on tDateStartedProphylaxis.person_id = tDemogrpahics.pid
+left join (
+select person_id, isEnrolled from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isEnrolled', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsEnrolled on tDemogrpahics.pid = tIsEnrolled.person_id
+
+
+UNION ALL
+SELECT
+ 'PCR test for HIV-Exposed Infants Upto 2 Months of age' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 2) and gender = 'M' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and pcrDateResult is not null and pcrDateResult between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')) THEN 1 END maleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 2) and gender = 'F' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and pcrDateResult is not null and pcrDateResult between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')) THEN 1 END femaleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 2) and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and pcrDateResult is not null and pcrDateResult between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')) THEN 1 END totalAll
+ FROM person pn
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship"))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_datetime AS 'pcrDateResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="HEI Testing (First PCR Test Date)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'heiResultDate', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'heiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (First PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+ UNION ALL
+
+
+Select
+'PCR test for HIV-Exposed Infants between 2-12 Months of age',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 12 and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 12 and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 2 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 12 and sex in ('F','M') then pid end)) as 'Total'
+
+ from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) >= 2 and TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) <= 12
+)tDemographics
+inner join (
+select pid , tConceptname.name as 'firstPcrTest', obs_datetime as 'firstpcrTestResultDate' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tFirstPCrTest on tDemographics.pidd = tFirstPCrTest.pid
+left join (
+select person_id , firstPcrTestDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'firstPcrTestDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFirstPCRTestDate on tDemographics.pidd = tFirstPCRTestDate.person_id
+
+
+UNION ALL
+
+Select
+'PCR test for HIV-Exposed Infants between 12-18 Months of age',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 18 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 18 and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 18 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 18 and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and firstPcrTest is not null and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstpcrTestResultDate) <= 18 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) >= 12 and TIMESTAMPDIFF(MONTH,date_of_birth, firstPcrTestDate) <= 18 and sex in ('F','M') then pid end)) as 'Total'
+
+ from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) >= 12 and TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) <= 18
+)tDemographics
+inner join (
+select pid , tConceptname.name as 'firstPcrTest', obs_datetime as 'firstpcrTestResultDate' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tFirstPCrTest on tDemographics.pidd = tFirstPCrTest.pid
+left join (
+select person_id , firstPcrTestDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'firstPcrTestDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFirstPCRTestDate on tDemographics.pidd = tFirstPCRTestDate.person_id
+
+
+UNION ALL
+
+SELECT
+ 'Total number of results received from Public Health laboratory\n(regardless sample collected)' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and datePhl is not null ) THEN 1 END maleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and datePhl is not null) THEN 1 END femaleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and datePhl is not null) THEN 1 END totalAll
+
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_datetime AS 'datePhl' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date sample receipt by PHL confirmed(First PCR Test)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Number of results received from Public Health Laboratory\n (Only from sample collected this month)' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and datePhl is not null ) THEN 1 END maleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and datePhl is not null) THEN 1 END femaleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and datePhl is not null) THEN 1 END totalAll
+
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_datetime AS 'datePhl' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date sample receipt by PHL confirmed(First PCR Test)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total number of positive results received' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM (
+ SELECT
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END maleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END femaleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END totalAll
+ FROM person pn
+
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_coded AS 'heiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (First PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'rapidheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Rapid Test At 9 Months Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS rr ON (rr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'secondheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Second PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS sr ON (sr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'repeatheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Repeat PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS er ON (er.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'eightrapidheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (18Months Rapid Test Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship"))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN concept_name cnpr ON (cnpr.concept_name_type = "FULLY_SPECIFIED" AND cnpr.voided is false AND cnpr.name="HEI Results Positive")
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total number of positive results received\n(only from samples collected this reporting months)' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM (
+ SELECT
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END maleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END femaleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and heiResult = cnpr.concept_id and rapidheiResult = cnpr.concept_id and secondheiResult = cnpr.concept_id and repeatheiResult = cnpr.concept_id and eightrapidheiResult = cnpr.concept_id) THEN 1 END totalAll
+ FROM person pn
+
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_coded AS 'heiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (First PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'rapidheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Rapid Test At 9 Months Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS rr ON (rr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'secondheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Second PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS sr ON (sr.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'repeatheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (Repeat PCR Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS er ON (er.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',o.value_coded AS 'eightrapidheiResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HEI Testing (18Months Rapid Test Results)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship"))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN concept_name cnpr ON (cnpr.concept_name_type = "FULLY_SPECIFIED" AND cnpr.voided is false AND cnpr.name="HEI Results Positive")
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Number of HIV Infected Infants started on ART' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and arvDateProphylaxis is not null ) THEN 1 END maleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and arvDateProphylaxis is not null) THEN 1 END femaleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and arvDateProphylaxis is not null) THEN 1 END totalAll
+
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_datetime AS 'arvDateProphylaxis' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date of ARV Prophylaxis Start" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+
+UNION ALL
+
+SELECT
+ 'Number of EID Samples rejected by Public Health Laboratory' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and pcrResult is not null and pcrResult = 1 and rapidTestresult is not null and rapidTestresult = 1 and secondresult is not null and secondresult = 1 and repeatresult is not null and repeatresult = 1 and 18repeatresult is not null and 18repeatresult = 1) THEN 1 END maleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and pcrResult is not null and pcrResult = 1 and rapidTestresult is not null and rapidTestresult = 1 and secondresult is not null and secondresult = 1 and repeatresult is not null and repeatresult = 1 and 18repeatresult is not null and 18repeatresult = 1 ) THEN 1 END femaleGender,
+ CASE WHEN ( (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and pcrResult is not null and pcrResult = 1 and rapidTestresult is not null and rapidTestresult = 1 and secondresult is not null and secondresult = 1 and repeatresult is not null and repeatresult = 1 and 18repeatresult is not null and 18repeatresult = 1 ) THEN 1 END totalAll
+
+ FROM person pn
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship"))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_coded AS 'pcrResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Was Sample Rejected(First PCR Test)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate2', o.value_coded AS 'rapidTestresult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Was Sample Rejected(Rapid Test At 9 Months)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate3', o.value_coded AS 'secondresult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Was Sample Rejected(Second PCR Test)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS sr ON (sr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate4', o.value_coded AS 'repeatresult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Was Sample Rejected(Repeat PCR Test)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS rr ON (rr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate4', o.value_coded AS '18repeatresult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Was Sample Rejected(18Months Rapid Test)" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS rs ON (rs.visitPatientId = pn.person_id)
+ ) p
+
+
+UNION ALL
+
+SELECT
+ 'HIV-Exposed Infants Upto 2 Months on Cotrimoxazole' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+ FROM(
+ SELECT
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'M' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and cotrimoxazoleResult is not null and cotrimoxazoleResult = 1 ) THEN 1 END maleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and gender = 'F' and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and cotrimoxazoleResult is not null and cotrimoxazoleResult = 1 ) THEN 1 END femaleGender,
+ CASE WHEN ((TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18) and MONTH(obsDate) = MONTH(CURDATE()) AND YEAR(obsDate) = YEAR(CURDATE()) and cotrimoxazoleResult is not null and cotrimoxazoleResult = 1 ) THEN 1 END totalAll
+ FROM person pn
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship"))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.obs_datetime AS 'obsDate', o.value_coded AS 'cotrimoxazoleResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Cotrimoxazole/Dapsone" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+select 'Number HIV-exposed infants received AZT+NVP',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+ from (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and (datediff('#endDate#',p.birthdate) / 365) < 2
+)tDemogrpahics
+left join (
+select person_b as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)tMother on tDemogrpahics.pid = tMother.hei_id
+inner join (
+select person_id, (select name from concept_name where concept_id = babyArvs and concept_name_type = 'FULLY_SPECIFIED') as 'babyArvs' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'babyArvs', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Baby Discharged with' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'AZT+NVP' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Baby Discharged with' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvBabyDischargedWith on tMother.mother_id = tArvBabyDischargedWith.person_id
+
+
+UNION ALL
+
+select 'Number HIV-exposed infants received NVP',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+ from (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and (datediff('#endDate#',p.birthdate) / 365) < 2
+)tDemogrpahics
+left join (
+select person_b as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)tMother on tDemogrpahics.pid = tMother.hei_id
+inner join (
+select person_id, (select name from concept_name where concept_id = babyArvs and concept_name_type = 'FULLY_SPECIFIED') as 'babyArvs' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'babyArvs', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Baby Discharged with' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'NVP' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Baby Discharged with' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvBabyDischargedWith on tMother.mother_id = tArvBabyDischargedWith.person_id
+
+
+UNION ALL
+
+
+select 'Number HIV-exposed infants received ARV prophylaxis\n(NVP and AZT + NVP) within first 6 weeks',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+from (
+select person_id , dateStartedProphylaxis from (
+select person_id, (SELECT @a:= 0) AS a , concept_id, value_datetime as 'dateStartedProphylaxis' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of ARV Prophylaxis Start' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and value_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of ARV Prophylaxis Start' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and value_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateStartedProphylaxis
+inner join (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and (datediff('#endDate#',p.birthdate) / 365) < 2 and (datediff(DATE_FORMAT('#endDate#','%Y-%m-01'),p.birthdate) / 7) <= 6
+)tDemogrpahics on tDateStartedProphylaxis.person_id = tDemogrpahics.pid
+
+
+UNION ALL
+
+select 'HIV-exposed infants whose \n feeding practice was assessed' as 'Title',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+from (
+
+select person_id, infantFeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'infantFeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Feeding' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Feeding' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tInfantFeeding
+inner join (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and (datediff('#endDate#',p.birthdate) / 365) < 2
+)tDemogrpahics on tInfantFeeding.person_id = tDemogrpahics.pid
+
+
+UNION ALL
+
+SELECT
+ 'Total HIV-exposed Infants turned \n 12 months of age in this reporting period' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+FROM (
+ SELECT
+ CASE WHEN ((pa.value = (select concept_id from concept_name where name = "HeiRelationship") or pa.value = (select concept_id from concept_name where name = "ExistingHeiRelationship")) and (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 12 and gender = 'M') ) THEN 1 END maleGender,
+ CASE WHEN ((pa.value = (select concept_id from concept_name where name = "HeiRelationship") or pa.value = (select concept_id from concept_name where name = "ExistingHeiRelationship")) and (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 12 and gender = 'F') ) THEN 1 END femaleGender,
+ CASE WHEN ((pa.value = (select concept_id from concept_name where name = "HeiRelationship") or pa.value = (select concept_id from concept_name where name = "ExistingHeiRelationship")) and (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 12) ) THEN 1 END totalAll
+ FROM visit v
+ LEFT JOIN person p1 on p1.person_id = v.patient_id
+ LEFT JOIN person_attribute pa on pa.person_id = p1.person_id
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+) p
+
+
+UNION ALL
+
+SELECT
+ 'Received initial PCR test between 2–12 months' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 2 and 12 and gender = 'M' and rapidTestResult is not null) THEN 1 END maleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 2 and 12 and gender = 'F' and rapidTestResult is not null) THEN 1 END femaleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 2 and 12 and rapidTestResult is not null) THEN 1 END totalAll
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'rapidTestResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="HEI Testing (First PCR Results)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+select 'Received rapid HIV antibody test 9 months' as 'Title',
+count(distinct(case when pid is not null and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and sex in ('M','F') then pid end)) as 'Total'
+from (
+
+select person_id, infantFeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'infantFeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tInfantFeeding
+inner join (
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and (TIMESTAMPDIFF(MONTH, p.birthdate, '#endDate#')) <= 9
+)tDemogrpahics on tInfantFeeding.person_id = tDemogrpahics.pid
+
+UNION ALL
+
+SELECT
+ 'Total HIV-exposed infants turned\n18 months in this reporting period' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 and gender = 'M' ) THEN 1 END maleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 and gender = 'F' ) THEN 1 END femaleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 ) THEN 1 END totalAll
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total number of children tested using Anti body rapid teast at 18 months' as 'Title',
+ count(maleGender) as 'Male',
+ count(femaleGender) as 'Female',
+ count(totalAll) as 'Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 and gender = 'M' and rapidTestResult is not null) THEN 1 END maleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 and gender = 'F' and rapidTestResult is not null) THEN 1 END femaleGender,
+ CASE WHEN (TIMESTAMPDIFF(MONTH, birthdate, CURDATE()) between 0 and 18 and rapidTestResult is not null) THEN 1 END totalAll
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'rapidTestResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="HEI Testing (18Months Rapid Test Results)" AND o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+select 'Exposed infant at 18months HIV- positive',
+count(distinct(case when pid is not null and Results18months = 'Positive' and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and Results18months = 'Positive' and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and Results18months = 'Positive' and sex in ('M','F') then pid end)) as 'Total'
+ from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and DATE_FORMAT(p.birthdate,'%Y-%m') = DATE_FORMAT(DATE_SUB(LAST_DAY('#endDate#'), INTERVAL 18 MONTH),'%Y-%m')
+)tDemographics
+inner join(
+select pid , tConceptname.name as 'Results18months' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)t18MonthsOutcome on tDemographics.pidd = t18MonthsOutcome.pid
+
+
+UNION ALL
+
+select 'Exposed infant at 18months HIV- negative and breastfeeding',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'EBF' and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'EBF' and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'EBF' and sex in ('M','F') then pid end)) as 'Total'
+ from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and DATE_FORMAT(p.birthdate,'%Y-%m') = DATE_FORMAT(DATE_SUB(LAST_DAY('#endDate#'), INTERVAL 18 MONTH),'%Y-%m')
+)tDemographics
+inner join(
+select pid , tConceptname.name as 'Results18months' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)t18MonthsOutcome on tDemographics.pidd = t18MonthsOutcome.pid
+left join (
+select breastfeeding_pid , tConceptname.name as 'breastfeedingResults' from (
+select distinct(person_id) as breastfeeding_pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tBreastFeeding on tDemographics.pidd = tBreastFeeding.breastfeeding_pid
+
+
+UNION ALL
+
+select 'Exposed infant at 18months HIV- negative and no longer breastfeeding',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'No longer Breastfeed' and sex = 'M' then pid end)) as 'Male',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'No longer Breastfeed' and sex = 'F' then pid end)) as 'Female',
+count(distinct(case when pid is not null and Results18months = 'Negative' and breastfeedingResults = 'No longer Breastfeed' and sex in ('M','F') then pid end)) as 'Total'
+ from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and DATE_FORMAT(p.birthdate,'%Y-%m') = DATE_FORMAT(DATE_SUB(LAST_DAY('#endDate#'), INTERVAL 18 MONTH),'%Y-%m')
+)tDemographics
+inner join(
+select pid , tConceptname.name as 'Results18months' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)t18MonthsOutcome on tDemographics.pidd = t18MonthsOutcome.pid
+left join (
+select breastfeeding_pid , tConceptname.name as 'breastfeedingResults' from (
+select distinct(person_id) as breastfeeding_pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tBreastFeeding on tDemographics.pidd = tBreastFeeding.breastfeeding_pid
+
diff --git a/openmrs/apps/reports/sql/HTS_Monthly_Report.sql b/openmrs/apps/reports/sql/HTS_Monthly_Report.sql
new file mode 100644
index 000000000..5d17196c6
--- /dev/null
+++ b/openmrs/apps/reports/sql/HTS_Monthly_Report.sql
@@ -0,0 +1,2080 @@
+
+select 'First Time Testers' as 'Title',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age < 1 and pat_id_tested is not null then pid end)) as '< 1 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 1 and age < 5 and pat_id_tested is not null then pid end)) as '1 - 4 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 5 and age < 10 and pat_id_tested is not null then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 10 and age < 15 and pat_id_tested is not null then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 15 and age < 20 and pat_id_tested is not null then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 20 and age < 25 and pat_id_tested is not null then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 25 and age < 30 and pat_id_tested is not null then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 30 and age < 35 and pat_id_tested is not null then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 35 and age < 40 and pat_id_tested is not null then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 40 and age < 45 and pat_id_tested is not null then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 45 and age < 50 and pat_id_tested is not null then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and age >= 50 and pat_id_tested is not null then pid end)) as '50+ YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'M' and pat_id_tested is null then pid end)) as 'Total MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age < 1 and pat_id_tested is not null then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 1 and age < 5 and pat_id_tested is not null then pid end)) as '1 - 4 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 5 and age < 10 and pat_id_tested is not null then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 10 and age < 15 and pat_id_tested is not null then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 15 and age < 20 and pat_id_tested is not null then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 20 and age < 25 and pat_id_tested is not null then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 25 and age < 30 and pat_id_tested is not null then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 30 and age < 35 and pat_id_tested is not null then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 35 and age < 40 and pat_id_tested is not null then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 40 and age < 45 and pat_id_tested is not null then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 45 and age < 50 and pat_id_tested is not null then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and age >= 50 and pat_id_tested is not null then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex = 'F' and pat_id_tested is not null then pid end)) as 'Total FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and first_testing_date is not null and retesting_date is null and sex in ('F','M') and pat_id_tested is not null then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select first_testing_date , firsttime_pid from (
+select person_id as firsttime_pid, concept_id, value_datetime as 'first_testing_date' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date First Tested HIV +' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pidd , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+ (select concept_id from concept_name where name = 'Date First Tested HIV +' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pidd) c on
+a.firsttime_pid = c.pidd and a.encounter_id = c.maxdate
+)tFirstTestingDate on tDemographics.pid = tFirstTestingDate.firsttime_pid
+left join (
+select retesting_date , secondTime_pid from (
+select person_id as secondTime_pid, concept_id, value_datetime as 'retesting_date' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime < DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pidd , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+ (select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime < DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pidd) c on
+a.secondTime_pid = c.pidd and a.encounter_id = c.maxdate
+)tRepeatTestingDate on tDemographics.pid = tRepeatTestingDate.secondTime_pid
+
+union all
+
+select 'Repeat Testers' as 'Title',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age < 1 and pat_id_tested is not null then firsttime_pid end)) as '< 1 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 1 and age < 5 and pat_id_tested is not null then firsttime_pid end)) as '1 - 4 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 5 and age < 10 and pat_id_tested is not null then firsttime_pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 10 and age < 15 and pat_id_tested is not null then firsttime_pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 15 and age < 20 and pat_id_tested is not null then firsttime_pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 20 and age < 25 and pat_id_tested is not null then firsttime_pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 25 and age < 30 and pat_id_tested is not null then firsttime_pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 30 and age < 35 and pat_id_tested is not null then firsttime_pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 35 and age < 40 and pat_id_tested is not null then firsttime_pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 40 and age < 45 and pat_id_tested is not null then firsttime_pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 45 and age < 50 and pat_id_tested is not null then firsttime_pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and age >= 50 and pat_id_tested is not null then firsttime_pid end)) as '50+ YRS MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'M' and pat_id_tested is not null then firsttime_pid end)) as 'Total MALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age < 1 and pat_id_tested is not null then firsttime_pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 1 and age < 5 and pat_id_tested is not null then firsttime_pid end)) as '1 - 4 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 5 and age < 10 and pat_id_tested is not null then firsttime_pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 10 and age < 15 and pat_id_tested is not null then firsttime_pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 15 and age < 20 and pat_id_tested is not null then firsttime_pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 20 and age < 25 and pat_id_tested is not null then firsttime_pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 25 and age < 30 and pat_id_tested is not null then firsttime_pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 30 and age < 35 and pat_id_tested is not null then firsttime_pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 35 and age < 40 and pat_id_tested is not null then firsttime_pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 40 and age < 45 and pat_id_tested is not null then firsttime_pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 45 and age < 50 and pat_id_tested is not null then firsttime_pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and age >= 50 and pat_id_tested is not null then firsttime_pid end)) as '50+ YRS FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex = 'F' and pat_id_tested is not null then firsttime_pid end)) as 'Total FEMALE',
+count(distinct(case when pat_id_tested = 'Newly Tested' and retesting_date is not null and sex in ('F','M') and pat_id_tested is not null then firsttime_pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select retesting_date , firsttime_pid from (
+select person_id as firsttime_pid, concept_id, value_datetime as 'retesting_date' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pidd , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+ (select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pidd) c on
+a.firsttime_pid = c.pidd and a.encounter_id = c.maxdate
+)tRepeatTestingDate on tDemographics.pid = tRepeatTestingDate.firsttime_pid
+
+union all
+select 'VCT(CITC) Tested ',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'VCT(CITC) +ve',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'VCT Clinic' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC TB Tested',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC TB +ve',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age < 1 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 1 and age < 5 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 5 and age < 10 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 10 and age < 15 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 15 and age < 20 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 20 and age < 25 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 25 and age < 30 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 30 and age < 35 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 35 and age < 40 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 40 and age < 45 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 45 and age < 50 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and age >= 50 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'M' and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age < 1 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 1 and age < 5 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 5 and age < 10 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 10 and age < 15 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 15 and age < 20 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 20 and age < 25 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 25 and age < 30 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 30 and age < 35 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 35 and age < 40 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 40 and age < 45 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 45 and age < 50 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and age >= 50 and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex = 'F' and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'TB Clinic' and sex in ('F','M') and pat_tb_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_tb_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsTBDiagnosized on tDemographics.pid = tIsTBDiagnosized.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC OPD Tested',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC OPD +ve',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Entry Point - OPD' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC Inpatient Tested',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC Inpatient +ve',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'In Patient' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC (Nutrition Unit) Tested',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC (Nutrition Unit) +ve',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Nutrition Unit' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC Pediatric Tested',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC Pediatric +ve',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Pediatric Clinic' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC (STI Clinic) Tested',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC (STI Clinic) +ve',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'STI Clinic' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'PITC ANC Tested',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'PITC ANC +ve',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'ANC Clinic' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'Others Tested',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'Others +ve',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Other Entry Point (Specify)' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+
+select
+'Index Case Contact Tested' as 'Title',
+count(distinct(case when Names is not null and ContactsAge < 1 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 1 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '1 - 4 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '5 - 9 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '10 - 14 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 15 - 19 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 20 - 24 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 25 - 29 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 30 - 34 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 36 - 40 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 40 - 44 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 45 - 49 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as '< 50+ YRS MALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and PatnerGender = 'M' then Names end)) as 'TOTAL MALE',
+count(distinct(case when Names is not null and ContactsAge < 1 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 1 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '1 - 4 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 15 - 19 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 20 - 24 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 25 - 29 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 30 - 34 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 36 - 40 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 40 - 44 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 45 - 49 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as '< 50+ YRS FEMALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and PatnerGender = 'F' then Names end)) as 'TOTAL FEMALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and PatnerGender in ('F','M') then Names end)) as 'Overall Total'
+
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b
+union all
+select
+'Index Case Contact +ve' as 'Title',
+count(distinct(case when Names is not null and ContactsAge < 1 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 1 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '1 - 4 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '5 - 9 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '10 - 14 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 15 - 19 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 20 - 24 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 25 - 29 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 30 - 34 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 36 - 40 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 40 - 44 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 45 - 49 YRS MALE',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'M' then Names end)) as '< 50+ YRS MALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and PatnerGender = 'M' and (newHivResults is not null or KnownPositiveResults is not null) then Names end)) as 'TOTAL MALE',
+count(distinct(case when Names is not null and ContactsAge < 1 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 1 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '1 - 4 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 15 - 19 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 20 - 24 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 25 - 29 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 30 - 34 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 36 - 40 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 40 - 44 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 45 - 49 YRS FEMALE',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as '< 50+ YRS FEMALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender = 'F' then Names end)) as 'TOTAL FEMALE',
+count(distinct(case when Names is not null and wasContactTested = 'YES' and (newHivResults is not null or KnownPositiveResults is not null) and PatnerGender in ('F','M') then Names end)) as 'Overall Total'
+
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b
+union all
+select 'Community Tested',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Community' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'Community +ve',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Community' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+union all
+select 'Total Key Population Tested',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age < 1 then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' and age >= 50 then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'M' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age < 1 then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 1 and age < 5 then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 5 and age < 10 then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 10 and age < 15 then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 15 and age < 20 then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 20 and age < 25 then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 25 and age < 30 then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 30 and age < 35 then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 35 and age < 40 then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 40 and age < 45 then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 45 and age < 50 then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' and age >= 50 then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex = 'F' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and pat_id_tested = 'Newly Tested' and sex in ('F','M') then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_tested' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+union all
+select 'Total Key Population Tested +ve',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'M' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total MALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age < 1 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '< 1 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 1 and age < 5 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '4 - 5 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 5 and age < 10 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '5 - 9 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 10 and age < 15 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '10 - 14 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 15 and age < 20 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '15 - 19 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 20 and age < 25 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '20 - 24 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 25 and age < 30 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '25 - 29 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 30 and age < 35 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '30 - 34 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 35 and age < 40 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '35 - 39 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 40 and age < 45 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '40 - 44 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 45 and age < 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '45 - 49 YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and age >= 50 and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as '50+ YRS FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex = 'F' and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Total FEMALE',
+count(distinct(case when entrypoint = 'Key Population Tested' and sex in ('F','M') and pat_id_positives = 'Newly Tested' and result_positives = 'Newly Tested HIV+' then pid end)) as 'Overall Total'
+from (
+select pid , tConceptname.name as 'entrypoint' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HIV - Entry Point' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers left join ( select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tDemographics
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tEnrtyPoint on tDemographics.pid = tEnrtyPoint.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'pat_id_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivPositives on tDemographics.pid = tHivPositives.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = hivStatus and concept_name_type = 'FULLY_SPECIFIED') as 'result_positives' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'hivStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Newly Tested HIV Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultPositive on tDemographics.pid = tResultPositive.person_id
+
+
+
+
+
+
+
+
+
+
diff --git a/openmrs/apps/reports/sql/PMTCT_ANC_visits_Syphilis_and_HBV_Testing.sql b/openmrs/apps/reports/sql/PMTCT_ANC_visits_Syphilis_and_HBV_Testing.sql
new file mode 100644
index 000000000..21a74ef9c
--- /dev/null
+++ b/openmrs/apps/reports/sql/PMTCT_ANC_visits_Syphilis_and_HBV_Testing.sql
@@ -0,0 +1,430 @@
+-- ANC Visits, Syphilis and HBV Testing
+
+SELECT
+ 'Total ANC Visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitNumberResult is not null THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitNumberResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitNumberResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F'and visitNumberResult is not null) THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and gender = 'F' and visitNumberResult is not null THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'visitNumberResult' , obs_datetime FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Visit Number" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'First ANC visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitResult = "1 = First Contact" THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and visitResult = "1 = First Contact") THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and (gender = 'F' and visitResult = "1 = First Contact") THEN 1 END totalAll
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'First ANC Mothers tested for Syphilis' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and (gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'First ANC Mothers testing Syphilis positive' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive" THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and (gender = 'F' and visitResult = "1 = First Contact" and rprvdrlResult = "Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Mothers tested for Syphilis (None First ANC visit mothers)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and (gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Mothers testing Syphilis positive (None First ANC visit mothers)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive" THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and (gender = 'F' and visitResult not in ("1 = First Contact") and rprvdrlResult = "Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+select
+'Attending ANC four visits' as 'Title',
+count(distinct(case when personid is not null and Age is null and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as 'Unknown age',
+count(distinct(case when personid is not null and Age >= 10 and Age < 15 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '10 - 14 YRS',
+count(distinct(case when personid is not null and Age >= 15 and Age < 20 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '15 - 19 YRS',
+count(distinct(case when personid is not null and Age >= 20 and Age < 25 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '20 - 24 YRS',
+count(distinct(case when personid is not null and Age >= 25 and Age < 30 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '25 - 29 YRS',
+count(distinct(case when personid is not null and Age >= 30 and Age < 35 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '30 - 34 YRS',
+count(distinct(case when personid is not null and Age >= 35 and Age < 40 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '35 - 39 YRS',
+count(distinct(case when personid is not null and Age >= 40 and Age < 45 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '40 - 44 YRS',
+count(distinct(case when personid is not null and Age >= 45 and Age < 50 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '45 - 49 YRS',
+count(distinct(case when personid is not null and Age >= 50 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as '50+ YRS',
+count(distinct(case when personid is not null and Age >= 10 and visitNumber = 'Fourth Visit' and gender = 'F' then personid end)) as 'Total'
+from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'TypeofPatient') and pa.value in ((select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED'),(select concept_id from concept_name where name = 'ExistingPatient' and concept_name_type = 'FULLY_SPECIFIED'),
+(select concept_id from concept_name where name = 'Transfer-In' and concept_name_type = 'FULLY_SPECIFIED')) and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created >= '#startDate#' and ob.date_created <= (DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59'))
+)tDemographics
+inner join (
+select pid , tConceptname.name as 'visitNumber' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Visit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Visit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tMaternityVisitNumber on tDemographics.personid = tMaternityVisitNumber.pid
+
+UNION ALL
+
+select
+'Attending ANC more than four visits' as 'Title',
+count(distinct(case when personid is not null and Age is null and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as 'Unknown age',
+count(distinct(case when personid is not null and Age >= 10 and Age < 15 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '10 - 14 YRS',
+count(distinct(case when personid is not null and Age >= 15 and Age < 20 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '15 - 19 YRS',
+count(distinct(case when personid is not null and Age >= 20 and Age < 25 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '20 - 24 YRS',
+count(distinct(case when personid is not null and Age >= 25 and Age < 30 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '25 - 29 YRS',
+count(distinct(case when personid is not null and Age >= 30 and Age < 35 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '30 - 34 YRS',
+count(distinct(case when personid is not null and Age >= 35 and Age < 40 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '35 - 39 YRS',
+count(distinct(case when personid is not null and Age >= 40 and Age < 45 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '40 - 44 YRS',
+count(distinct(case when personid is not null and Age >= 45 and Age < 50 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '45 - 49 YRS',
+count(distinct(case when personid is not null and Age >= 50 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as '50+ YRS',
+count(distinct(case when personid is not null and Age >= 10 and visitNumber in ('Fifth Visit','Sixth Visit','Seventh Visit','Eighth Visit','Ninth Visit') and gender = 'F' then personid end)) as 'Total'
+from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'TypeofPatient') and pa.value in ((select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED'),(select concept_id from concept_name where name = 'ExistingPatient' and concept_name_type = 'FULLY_SPECIFIED'),
+(select concept_id from concept_name where name = 'Transfer-In' and concept_name_type = 'FULLY_SPECIFIED')) and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created >= '#startDate#' and ob.date_created <= (DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59'))
+)tDemographics
+inner join (
+select pid , tConceptname.name as 'visitNumber' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Visit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Visit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tMaternityVisitNumber on tDemographics.personid = tMaternityVisitNumber.pid
+
+
+
+UNION ALL
+
+SELECT
+ 'Mothers tested for HBV ' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and visitNumberResult is not null THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and visitNumberResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and visitNumberResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F'and visitNumberResult is not null) THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and gender = 'F' and visitNumberResult is not null THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitNumberResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HBV" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Mothers tested HBV Positive' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN birthdate is null and gender = 'F' and hbvResult = "Positive" THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 10 and 14 and gender = 'F' and hbvResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 15 and 19 and gender = 'F' and hbvResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 20 and 24 and gender = 'F' and hbvResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 25 and 29 and gender = 'F' and hbvResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 30 and 34 and gender = 'F' and hbvResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 35 and 39 and gender = 'F' and hbvResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 40 and 44 and gender = 'F' and hbvResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') between 45 and 49 and gender = 'F' and hbvResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, '#endDate#') >= 50 and gender = 'F' and hbvResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN birthdate is not null and gender = 'F' and hbvResult = "Positive" THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hbvResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HBV" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id where obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+) p
diff --git a/openmrs/apps/reports/sql/PMTCT_Clients_who_received_ART.sql b/openmrs/apps/reports/sql/PMTCT_Clients_who_received_ART.sql
new file mode 100644
index 000000000..cf9ba9cff
--- /dev/null
+++ b/openmrs/apps/reports/sql/PMTCT_Clients_who_received_ART.sql
@@ -0,0 +1,1338 @@
+-- Number of PMTCT Clients who received ART during this reporting period by Regimen (Current on OptionB+)
+
+SELECT
+ 'Adult 1st Line Regimens:' as 'Regimen',
+ 'M' as '<10 Male',
+ 'F' as '<10 Female',
+ 'M' as'10-15 Male' ,
+ 'F' as'10-15 Female',
+ 'M' as '15-49 Male',
+ 'F' as '15-49 Female',
+ 'M' as '50+ Male',
+ 'F' as '50+ Female',
+ '' as 'Total',
+ '' as'BreastFeeding',
+ '' as 'Pregnant'
+ From DUAL
+
+UNION All
+select
+'1a = AZT/3TC+ EFV' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1a = AZT/3TC+EFV')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+
+
+
+
+
+UNION ALL
+select
+'1b = AZT/3TC/NVP' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1b = AZT/3TC/NVP')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+
+
+
+UNION ALL
+
+select
+'1c = TDF/3TC/DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1c = TDF/3TC/DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+
+UNION ALL
+
+select
+'1d=ABC/3TC (600/300)/DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1d=ABC/3TC (600/300)/DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+
+UNION ALL
+
+select
+'1e = AZT/3TC +DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1e = AZT/3TC +DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'1f = TDF/3TC+EFV' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1f = TDF/3TC+EFV')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+select
+'1g = TDF/3TC+NVP' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1g = TDF/3TC+NVP')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'1h = TDF/FTC/EFV' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('1h = TDF/FTC/EFV')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+SELECT
+ 'Adult 2nd Line Regimens:' as 'Regimen',
+ '' as '<10 Male',
+ '' as '<10 Female',
+ '' as'10-15 Male' ,
+ '' as'10-15 Female',
+ '' as '15-49 Male',
+ '' as '15-49 Female',
+ '' as '50+ Male',
+ '' as '50+ Female',
+ '' as 'Total',
+ '' as'BreastFeeding',
+ '' as 'Pregnant'
+From DUAL
+
+UNION ALL
+
+select
+
+'2a=AZT/3TC+DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2a=AZT/3TC+DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'2b=ABC/3TC+DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2b=ABC/3TC+DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'2c=TDF+3TC+LPV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2c=TDF+3TC+LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'2d=TDF/3TC+ATV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2d=TDF/3TC+ATV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'2e=TDF/FTC-LPV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2e=TDF/FTC-LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+select
+'2f=TDF/FTC-ATV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2f=TDF/FTC-ATV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+select
+'2g=AZT/3TC+LPV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2g=AZT/3TC+LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+select
+'2h=AZT/3TC+ATV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2h=AZT/3TC+ATV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+select
+'2i=ABC/3TC+LPV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2i=ABC/3TC+LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+UNION ALL
+select
+'2j=ABC/3TC+ATV/r' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2j=ABC/3TC+ATV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+select
+'2k=TDF/3TC/DTG' as 'Regimen',
+'N/A' as '<10 Male',
+count(distinct(case when patient_id is not null and Age < 10 and gender = 'F' then patient_id end)) as '<10 Female',
+'N/A' as '10 - 15 Male',
+count(distinct(case when patient_id is not null and Age >= 10 and Age <15 and gender = 'F' then patient_id end)) as '10 - 15 Female',
+'N/A' as '15 - 49 Male',
+count(distinct(case when patient_id is not null and Age >= 15 and Age < 50 and gender = 'F' then patient_id end)) as '15 - 49 Female',
+'N/A' as '50+ Male',
+count(distinct(case when patient_id is not null and Age >= 50 and gender = 'F' then patient_id end)) as '50+ Female',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' then patient_id end)) as 'Total',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and breastFeeding = 'YES' then patient_id end)) as 'Breastfeeding',
+count(distinct(case when patient_id is not null and Age > 0 and gender = 'F' and pregnant = 'YES' then patient_id end)) as 'Pregant'
+
+from(
+select patient_id, Age, gender
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped , p.birthdate , p.gender ,
+(TIMESTAMPDIFF(YEAR, p.birthdate, '#endDate#')) as 'Age'
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+left join person p on o.patient_id = p.person_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name = ('2k=TDF/3TC/DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate and gender = 'F'
+)t1a left join (
+select person_id , (case when pregnantResult = 1 then 'YES' else 'NO' end) as 'pregnant' from (
+select person_id, pregnantResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pregnantResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'pregnant' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.pregnantResult = tConceptname.concept_id
+)tpregnant on t1a.patient_id = tpregnant.person_id
+left join(
+select person_id , (case when breastFeedingResult = 1 then 'YES' else 'NO' end) as 'breastFeeding' from (
+select person_id, breastFeedingResult from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'breastFeedingResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'breastfeeding' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.breastFeedingResult = tConceptname.concept_id
+)tBreastFeeding on t1a.patient_id = tBreastFeeding.person_id
+
+UNION ALL
+
+SELECT
+ 'No signs of TB' as 'Regimen',
+ count(belowtenmale) as '<10 Male',
+ count(belowtenfemale) as '<10 Female',
+ count(tenTofifteenmale) as '10-15 Male',
+ count(tenTofifteenfemale) as '10-15 Female',
+ count(fifteenTOfourtyninemale) as '15-49 Male',
+ count(fifteenTOfourtyninefemale) as '15-49 Female',
+ count(overFiftymale) as '50+ Male',
+ count(overFiftyfemale) as '50+ Female',
+ count(totalAll) as 'Total',
+ count(breastfeeding) as 'BreastFeeding',
+ count(pregnant) as 'Pregnant'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 10 and gender = 'M' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END belowtenmale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 10 and gender = 'F' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END belowtenfemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 15 and gender = 'M' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END tenTofifteenmale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 15 and gender = 'F' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END tenTofifteenfemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 49 and gender = 'M' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END fifteenTOfourtyninemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 49 and gender = 'F' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END fifteenTOfourtyninefemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 115 and gender = 'M' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END overFiftymale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 115 and gender = 'F' and cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END overFiftyfemale,
+ CASE WHEN (cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END totalAll,
+ CASE WHEN (cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END breastfeeding,
+ CASE WHEN (cuCoughResult = "False" and tbFeverResult = "False" and tbWeightResult = "False" and tbNightsResult = "False") THEN 1 END Pregnant
+FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'cuCoughResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Current Cough" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS cr ON (cr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbFeverResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening , Fever" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS fr ON (fr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbWeightResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening ,Weight loss" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS wr ON (wr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbNightsResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening , Night Sweats" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS nr ON (nr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Presumptive TB case' as 'Regimen',
+ count(belowtenmale) as '<10 Male',
+ count(belowtenfemale) as '<10 Female',
+ count(tenTofifteenmale) as '10-15 Male',
+ count(tenTofifteenfemale) as '10-15 Female',
+ count(fifteenTOfourtyninemale) as '15-49 Male',
+ count(fifteenTOfourtyninefemale) as '15-49 Female',
+ count(overFiftymale) as '50+ Male',
+ count(overFiftyfemale) as '50+ Female',
+ count(totalAll) as 'Total',
+ count(breastfeeding) as 'BreastFeeding',
+ count(pregnant) as 'Pregnant'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 10 and gender = 'M' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END belowtenmale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 10 and gender = 'F' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END belowtenfemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 15 and gender = 'M' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END tenTofifteenmale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 15 and gender = 'F' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END tenTofifteenfemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 49 and gender = 'M' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END fifteenTOfourtyninemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 49 and gender = 'F' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END fifteenTOfourtyninefemale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 115 and gender = 'M' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END overFiftymale,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 115 and gender = 'F' and cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END overFiftyfemale,
+ CASE WHEN (cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END totalAll,
+ CASE WHEN (cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END breastfeeding,
+ CASE WHEN (cuCoughResult = "True" and tbFeverResult = "True" and tbWeightResult = "True" and tbNightsResult = "True") THEN 1 END Pregnant
+FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'cuCoughResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Current Cough" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS cr ON (cr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbFeverResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening , Fever" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS fr ON (fr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbWeightResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening ,Weight loss" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS wr ON (wr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'tbNightsResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="TB Screening , Night Sweats" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS nr ON (nr.visitPatientId = pn.person_id)
+) p
+
+UNION All
+
+SELECT
+ 'Not Assesed' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'TB RX' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
diff --git a/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_ANC_Clinic.sql b/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_ANC_Clinic.sql
new file mode 100644
index 000000000..396836de0
--- /dev/null
+++ b/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_ANC_Clinic.sql
@@ -0,0 +1,371 @@
+
+
+SELECT
+ 'Known positive status (at entry into ANC) - a' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Known positive status at entry into ANC on ART' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'artResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Transferred in on ART?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status tested for HIV (1st ANC Visit) -b' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status testing HIV positive (1st ANC visit)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total of HIV Positive women \n attending ANC (a+b)'as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypointhiv' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS hr ON (hr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'HIV infected pregnant women newly started on ART (Option B+)'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'artResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Transferred in on ART?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'arvsResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Were ARVS Received?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS ar ON (ar.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total of HIV Positive \n Pregnant women enrolled in PMTCT'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pregResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="FP Pregnant" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pmtcrResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="PMTCT - HIV & ART Follow up" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS ar ON (ar.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Known positive status on ART Breastfeeding 'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True" ) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint = "ANC Clinic" and pregResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pregResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Currently Breastfeeding?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
diff --git a/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_Maternity.sql b/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_Maternity.sql
new file mode 100644
index 000000000..54e588f8b
--- /dev/null
+++ b/openmrs/apps/reports/sql/PMTCT_Counseling_and_Testing_Maternity.sql
@@ -0,0 +1,196 @@
+-- HIV Counseling and Testing at Maternity
+
+SELECT
+ 'Mothers delivered in this facility (Total)' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Known positive status at admision into maternity ' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Known positive status at\nadmision into maternity on ART' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Women of Unknown HIV Status at\nadmission into maternity' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status tested for HIV in maternity' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status testing HIV positive at maternity' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'women testing HIV positive in maternity started on ART (new)' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Total of HIV positive women delivered ' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+UNION ALL
+
+SELECT
+ 'Infants started on Nevirapine Prohylaxis ' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitNumberResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitNumberResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F'and visitNumberResult is not null) THEN 1 END overFifty,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END totalAll
+
+ FROM visit v
+ JOIN person pn on pn.person_id = v.patient_id
+ JOIN person_attribute pa on pa.person_id = pn.person_id and pa.value in (select concept_id from concept_name where name in ("HeiRelationship", "ExistingHeiRelationship" ))
+ JOIN person_attribute_type pat on (pat.person_attribute_type_id = pa.person_attribute_type_id and pat.retired = 0 and pat.name = "TypeofPatient")
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'visitNumberResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Date of ARV Prophylaxis Start" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Infants linked to HEI Care ' as 'Title',
+ '' as 'Unknown age',
+ ''as '10-14 YRS',
+ '' as '15-19 YRS',
+ '' as '20-24 YRS',
+ '' as '25-29 YRS',
+ '' as '30-34 YRS',
+ '' as '35-39 YRS',
+ '' as '40-44 YRS',
+ '' as '45-49 YRS',
+ '' as '50+ YRS',
+ '' as 'Total'
+from dual
+
+
diff --git a/openmrs/apps/reports/sql/anc_pmtct_register.sql b/openmrs/apps/reports/sql/anc_pmtct_register.sql
new file mode 100644
index 000000000..1ad93b460
--- /dev/null
+++ b/openmrs/apps/reports/sql/anc_pmtct_register.sql
@@ -0,0 +1,446 @@
+select concat(coalesce(given_name,''),' ', coalesce(middle_name,'') ,' ',coalesce(family_name,'') ) as 'Full Names', ancRegistrationDate as 'Anc Registration Date' , results as 'Occupation' , ancNo as 'ANC Number/Surveillance ID', pmtctEntry as 'Entry to PMTCT' , treatmentStatus as 'Treatment Status',
+(case when hivRetestingDate is not null then 'Yes' else 'No' end) as 'HIV Retesting for ART initiation?', uartNumber as 'Unique ART No.', artStartDate as 'Date Initiated On ART', Cohort ,Age ,concat("Address : ", (case when Address is null then 'N/A' else mobile end) , "\n", "Mobile : ", mobile) as 'Address',
+LNMP , edd as 'EDD' , gestationPeriodWeeks as 'Gestational age in weeks (GA)', weight as 'Weight(Kgs)' , muac as 'Mid-Upper Arm Circumference (MUAC)', TBStatus as 'TB Status', whoResults as 'WHO Stage', cd4 as 'CD4' ,partnerResult as 'Partner Result', Ctxresults as 'CTX=Contrimoxazole or DAP=Dapsone' , tbRxDate as 'TB Rx start Date', TbUnitNumber as 'Tb Reg No.',
+dateVlCollected as 'Date VL SampleCollected', VlResults as 'VL result (Value)',firstregimen as '1st Line Regimen - Original Regimen', firstsubstitutionregimen as '1st Line Regimen - 1st: Substitution drug code' , secondswitchwithinfirstline as '1st Line Regimen - 2nd: Substitution drug code' , secondlinefirst as '2nd Line Regimen - 2nd Line Regimen switched to',
+firstsubstitutionwithinsecond as '2nd Line Regimen - 1st: Substitution drug code',
+secondsubstitutionwithinsecondline as '2nd Line Regimen - 2nd: Substitution drug code', dateOfDelivery as 'Date Of Delivery' , PlaceOfDeliveryresults as 'Place of Delivery', DeliveryOutocomeresults as 'Delivery Outcome', prophylaxisResults as 'Infant Received Prophylaxis?' ,heinumber as 'Exposed Infant Number'
+ from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'TypeofPatient') and pa.value in ((select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED'),(select concept_id from concept_name where name = 'ExistingPatient' and concept_name_type = 'FULLY_SPECIFIED'),
+(select concept_id from concept_name where name = 'Transfer-In' and concept_name_type = 'FULLY_SPECIFIED')) and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created >= '#startDate#' and ob.date_created <= (DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59'))
+)tDemographics
+left join (
+select person_id , ancRegistrationDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'ancRegistrationDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC Clinic Registration Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC Clinic Registration Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAncRegistrationDate on tDemographics.personid = tAncRegistrationDate.person_id
+left join (
+select person_id , results from (
+select person_id, occupation from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'occupation', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Occupation' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Occupation' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'results' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.occupation = tConceptname.concept_id
+)tResultswithin6Months on tDemographics.personid = tResultswithin6Months.person_id
+left join(
+select person_id, ancNo from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'ancNo', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_text is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAncNo on tDemographics.personid = tAncNo.person_id
+left join (
+select person_id , results as 'pmtctEntry' from (
+select person_id, pmtctEntry from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'pmtctEntry', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Entry to PMTCT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Entry to PMTCT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'results' from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tresults.pmtctEntry = tConceptname.concept_id
+)tEntryToPmtct on tDemographics.personid = tEntryToPmtct.person_id
+left join (
+select person_id , hivRetestingDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'hivRetestingDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHivRetestingDate on tDemographics.personid = tHivRetestingDate.person_id
+left join (
+select person_id , artStartDate , DATE_FORMAT(artStartDate, '%Y-%m') as 'Cohort' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'artStartDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC, ART Start Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC, ART Start Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArtStartDate on tDemographics.personid = tArtStartDate.person_id
+left join(
+select pn.person_id as 'pid', pa.value as 'mobile' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id where pa.person_attribute_type_id
+=(select person_attribute_type_id from person_attribute_type where name = 'MobileNumber')
+)tMobile on tDemographics.personid = tMobile.pid
+left join (
+select person_id , concat(coalesce(concat("State: ",address1) , "N/A"), " " ,coalesce(concat("Boma: ",address4), ""), " ",coalesce(concat("Village: ",address5) , ""))
+as Address from person_address where preferred = 1
+) tpatientAddrress on tDemographics.personid = tpatientAddrress.person_id
+left join (
+select person_id , LNMP from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'LNMP', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of the first Day of LNMP' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of the first Day of LNMP' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tLNMPDate on tDemographics.personid = tLNMPDate .person_id
+left join (
+select person_id , edd from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'edd', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEDDDate on tDemographics.personid = tEDDDate.person_id
+left join(
+select person_id , gestationPeriodWeeks from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'gestationPeriodWeeks', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Gestation(Weeks)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Gestation(Weeks)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tGestationWeeks on tDemographics.personid = tGestationWeeks.person_id
+left join(
+select person_id , weight from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'weight', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'weight' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'weight' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tWeight on tDemographics.personid = tWeight.person_id
+left join(
+select person_id , muac from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'muac', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'MUAC, Pregnancy Visit' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'MUAC, Pregnancy Visit' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMuac on tDemographics.personid = tMuac.person_id
+left join (
+select person_id , (case when tbDiaognised = 1 then 'Positive' else 'Negative' end) as 'TBStatus' from (
+select person_id, tbDiaognised from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbDiaognised', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'tbResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.tbDiaognised = tConceptname.concept_id
+)tTBStatus on tDemographics.personid = tTBStatus.person_id
+left join (
+select person_id , whoResults from (
+select person_id, whoStage from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'whoStage', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'WHO Stage' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'WHO Stage' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'whoResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.whoStage = tConceptname.concept_id
+)tWHOStage on tDemographics.personid = tWHOStage.person_id
+left join(
+select person_id , cd4 from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'cd4', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCd4 on tDemographics.personid = tCd4.person_id
+left join (
+select person_id , tbRxDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'tbRxDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbRxDate on tDemographics.personid = tTbRxDate.person_id
+left join (
+select person_id , TbUnitNumber from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'TbUnitNumber', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Unit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Unit Number' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbUnitNumber on tDemographics.personid = tTbUnitNumber.person_id
+left join (
+select person_id , (case when Ctxresults = 'True' then 'Yes' else 'No' end) as 'Ctxresults' from (
+select person_id, ctxDapson from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'ctxDapson', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'Ctxresults' from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tresults.ctxDapson = tConceptname.concept_id
+)tCtxDapsone on tDemographics.personid = tCtxDapsone.person_id
+left join (
+select person_id , dateVlCollected from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dateVlCollected', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date VL Sample Collected?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date VL Sample Collected?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateVlCollected on tDemographics.personid = tDateVlCollected.person_id
+left join (
+select person_id , VlResults from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'VlResults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tVlResults on tDemographics.personid = tVlResults.person_id
+left join(
+select distinct(pid), firstregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)tfirstlinereg
+)tfirstlineregimen on tDemographics.personid = tfirstlineregimen.pid
+left join (
+select distinct(pid), firstsubstitutionregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)tSubRegimen
+)tFirstSubstitituionregime on tDemographics.personid = tFirstSubstitituionregime.pid
+left join (
+select distinct(pid), secondswitchwithinfirstline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondswitchwithinfirstline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)tsecoondfirstswithc
+)tSecondSubstitutionfirstline on tDemographics.personid = tSecondSubstitutionfirstline.pid
+ left join (
+ select distinct(pid), secondlinefirst from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondlinefirst' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)secondlinefirst
+)tSecondlineoriginal on tDemographics.personid = tSecondlineoriginal.pid
+left join (
+select distinct(pid), firstsubstitutionwithinsecond from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionwithinsecond' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)firstsubstitutionwithinsecond
+)tfirstsubstitutionwithinsecondline on tDemographics.personid = tfirstsubstitutionwithinsecondline.pid
+left join (
+select distinct(pid), secondsubstitutionwithinsecondline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondsubstitutionwithinsecondline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)secondsubstitutionwithinsecondline
+)tsecondsubstitutionwithinsecondline on tDemographics.personid = tsecondsubstitutionwithinsecondline.pid
+left join (
+select person_id , dateOfDelivery from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dateOfDelivery', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Post Natal,Date Of Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Post Natal,Date Of Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateOfDelivery on tDemographics.personid = tDateOfDelivery.person_id
+left join (
+select person_id , PlaceOfDeliveryresults from (
+select person_id, placeOfDelivery from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'placeOfDelivery', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Post Natal ,Place Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Post Natal ,Place Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'PlaceOfDeliveryresults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.placeOfDelivery = tConceptname.concept_id
+)tPlaceOfDelivery on tDemographics.personid = tPlaceOfDelivery.person_id
+left join (
+select person_id , DeliveryOutocomeresults from (
+select person_id, deliveryOutcome from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'deliveryOutcome', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Delivery Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Delivery Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'DeliveryOutocomeresults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.deliveryOutcome = tConceptname.concept_id
+)tDeliveryOutcome on tDemographics.personid = tDeliveryOutcome.person_id
+left join (
+select person_id , (case when ProphylaxisResults = 'True' then 'Yes' else 'No' end) as 'prophylaxisResults' from (
+select person_id, receivedProphylaxis from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'receivedProphylaxis', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Received ARV Prophylaxis at Birth' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Received ARV Prophylaxis at Birth' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'ProphylaxisResults' from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tresults.receivedProphylaxis = tConceptname.concept_id
+)tIsProhylaxisStarted on tDemographics.personid = tIsProhylaxisStarted.person_id
+left join (
+select mother_id, eid , heinumber from (
+select person_b as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)heiRelationship
+left join(
+select pa.person_id as 'eid', pa.value as 'heinumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No') and gender is not null
+)tHeiDemographics on heiRelationship.hei_id = tHeiDemographics.eid
+)tHeiNumber on tDemographics.personid = tHeiNumber.mother_id
+left join (
+select person_id , (select name from concept_name where concept_id = value and concept_name_type = 'SHORT') as 'treatmentStatus' from person_attribute where person_attribute_type_id =
+(select person_attribute_type_id from person_attribute_type where name = 'TransferInTreatmentStatus')
+)tUniqueARTNumber on tDemographics.personid = tUniqueARTNumber.person_id
+left join (
+select person_id , value as 'uartNumber' from person_attribute where person_attribute_type_id =
+(select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tUniqueArtNumber on tDemographics.personid = tUniqueArtNumber.person_id
+left join (
+select pidd, (case when hiv_result is null and hts_result is null then 'N/A' else case when hiv_result is not null and hts_result is not null then hts_result else case when hiv_result is not null and hts_result is null
+then hiv_result else case when hiv_result is null and hts_result is not null then hts_result end end end end) as 'partnerResult' from (
+select person_id as pidd, spouse, obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'spouse', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = (
+select concept_id from concept_name where name = 'Spouse' and concept_name_type = 'FULLY_SPECIFIED') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(obs_group_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner Relationship' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.obs_group_id = c.maxdate
+)tIsSpouse
+left join (
+select person_id, (select name from concept_name where concept_id = HivKnownStatus and concept_name_type = 'SHORT') as 'hiv_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'HivKnownStatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResult on tIsSpouse.obs_group_id = tSpouseHivResult.obs_group_id
+left join (
+select person_id, (select name from concept_name where concept_id = NewTestedResult and concept_name_type = 'SHORT') as 'hts_result', obs_group_id from (
+select person_id, concept_id, obs_datetime , obs_group_id, encounter_id , value_coded as 'NewTestedResult', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSpouseHivResultAfterTesting on tIsSpouse.obs_group_id = tSpouseHivResultAfterTesting.obs_group_id
+)tSpouseHivStatus on tDemographics.personid = tSpouseHivStatus.pidd
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/ancpmtctDischargeTab.sql b/openmrs/apps/reports/sql/ancpmtctDischargeTab.sql
new file mode 100644
index 000000000..369abe393
--- /dev/null
+++ b/openmrs/apps/reports/sql/ancpmtctDischargeTab.sql
@@ -0,0 +1,50 @@
+Select concat(coalesce(given_name,''),' ', coalesce(middle_name,'') ,' ',coalesce(family_name,'') ) as 'Full Names' ,value as 'Unique ART Number',
+tMaternalOutcome.maternal_outcome as 'Maternal outcome at last follow up', tInfantfinalstatus.infant_final_status as 'Infant Final Status' ,
+tDateMotherTranferredtoArt.Date_mother_transferred_to_art as 'Date mother/baby transferred to ART', tInfantsArtNumber.infants_art_number as 'infants_art_number'
+ from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created between '#startDate#' and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tUniqueART
+left join
+(
+select distinct(person_id) , concept_short_name as 'maternal_outcome' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Maternal Outcome(last Follow up)' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)maternalOutcome
+)tMaternalOutcome on tUniqueART.personid = tMaternalOutcome.person_id
+left join
+(
+select distinct(person_id) , concept_short_name as 'infant_final_status' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) c on obs.person_id = c.person_id and obs.encounter_id = c.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where uuid = '547114dd-fa20-4a8b-8df9-4ac17a922423' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)infantfinalstatus
+)tInfantfinalstatus on tUniqueART.personid = tInfantfinalstatus.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'Date_mother_transferred_to_art'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Date Mother/Baby Transferred to ART' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tDateMotherTranferredtoArt on tUniqueART.personid = tDateMotherTranferredtoArt.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_text as 'infants_art_number'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Infants ART Number(For Confimed Positive Infants)' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tInfantsArtNumber on tUniqueART.personid = tInfantsArtNumber.person_id
+
diff --git a/openmrs/apps/reports/sql/ancreport.sql b/openmrs/apps/reports/sql/ancreport.sql
new file mode 100644
index 000000000..102fc29b5
--- /dev/null
+++ b/openmrs/apps/reports/sql/ancreport.sql
@@ -0,0 +1,338 @@
+select tDateRegisteredToANC.Date_Registered_into_ANC as 'Date Registered into ANC', concat(coalesce(given_name,''),' ', coalesce(middle_name,'') ,' ',coalesce(family_name,'') ) as 'Full Names', tOccupation.Occupation ,tANCNumber.ANC_Number as 'ANC Number/Surveillance ID' ,tEntryTopmtct.Entry_to_PMTCT as 'Entry to PMTCT' , tTreatmentStatus.treatment_status as 'Treatment status',
+tRetestingDate.Retesting as 'HIV Retesting for ART initiation?' ,value as 'Unique ART No.' ,tARTStartDate.ARTStartDate as 'Date Initiated On ART', tCohort.Cohort as 'Cohort Months' ,tUniqueART.Age as 'Age' , concat(tpatientAddrress.Address," ","\n",concat("Mobile Number: ",tMobileNumber.mobile)) as 'Address',
+tLNMPDate.LNMP as 'LNMP' , tEDDDate.EDD as 'EDD' , tGestationPeriod.Gestationalage as 'Gestational age in weeks (GA)', tWeight.weight as 'Weight(Kg)', tMUAC.muac as 'Mid-Upper Arm Circumference (MUAC)',
+tTBDiagnosd.TBStatus , tWHOStage.whostage as 'WHO Stage' , tCdfour.cdfour as 'CD4 COUNT', tHivResult.partnerResult as 'Partner Result', tCotrimoxazole.Cotrimoxazole as 'CTX=Contrimoxazole or DAP=Dapsone',
+tBrx.tbrx as 'TB Rx start', tbRegNumber.tbRegNo as 'TB Reg No.', tDateVLCollected.dateVLSampleCollected as 'Date VL SampleCollected' , tVLResults.VLResults as 'VL result (Value)',
+firstregimen as '1st Line Regimen - Original Regimen', firstsubstitutionregimen as '1st Line Regimen - 1st: Substitution drug code' , secondswitchwithinfirstline as '1st Line Regimen - 2nd: Substitution drug code' , secondlinefirst as '2nd Line Regimen - 2nd Line Regimen switched to',
+firstsubstitutionwithinsecond as '2nd Line Regimen - 1st: Substitution drug code',
+secondsubstitutionwithinsecondline as '2nd Line Regimen - 2nd: Substitution drug code' ,
+tDateOfDelivery.Date_Of_Delivery as 'Date Of Delivery', tplaceofDelivery.place_of_delivery as 'Place of Delivery',
+tdeliveryoutcome.delivery_outcome as 'Delivery Outcome' , tInfantReceivedProphylaxis.InfantReceivedProphylaxis as 'Infant Received Prophylaxis?' , tHeiNumber.HeiNumber as 'Exposed Infant Number'
+ from (
+select distinct(pn.person_id) as 'personid', pn.given_name, pn.middle_name, pn.family_name, pa.value , p.gender as 'gender' , TIMESTAMPDIFF(YEAR,birthdate,NOW()) as 'Age' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id
+left join person p on pn.person_id = p.person_id
+left join obs ob on pa.person_id = ob.person_id
+where pa.person_attribute_type_id
+= (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and p.gender = 'F'
+and concept_id = (select concept_id from concept_name where name = 'HIV - Entry Point'
+and concept_name_type = 'fully_specified' ) and
+value_coded = (select concept_id from concept_name where name = 'ANC Clinic' and concept_name_type = 'fully_specified')
+and ob.date_created >= '#startDate#' and ob.date_created <= (DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59'))
+)tUniqueART
+left join(
+select pid , mobile from (
+select pn.person_id as 'pid', pn.given_name, pn.middle_name, pa.value as 'mobile' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id where pa.person_attribute_type_id
+=(select person_attribute_type_id from person_attribute_type where name = 'MobileNumber')
+)tMobile
+)tMobileNumber on tUniqueART.personid = tMobileNumber.pid
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'Date_Registered_into_ANC'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'ANC Clinic Registration Date' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tDateRegisteredToANC on tUniqueART.personid = tDateRegisteredToANC.person_id
+left join
+(
+select obs.person_id,obs.concept_id , TIMESTAMPDIFF(MONTH,obs.value_datetime , curdate()) as 'Cohort'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'ANC, ART Start Date' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tCohort on tUniqueART.personid = tCohort.person_id
+left join
+(
+select distinct(person_id) , concept_short_name as 'Occupation' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Occupation' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)tOccupa
+)tOccupation on tUniqueART.personid = tOccupation.person_id
+left join(
+select obs.person_id,obs.concept_id , obs.value_text as 'ANC_Number'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'ANC No' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+) tANCNumber on tUniqueART.personid = tANCNumber.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'Dateretested' ,
+(case when obs.value_datetime is not null then 'Yes' else 'No' end) as 'Retesting'
+ from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Date of HIV Retesting Before ART' and cn.concept_name_type = 'fully_specified' group by obs.person_id
+)tRetestingDate on tUniqueART.personid = tRetestingDate.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'ARTStartDate'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'ANC, ART Start Date' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+) tARTStartDate on tUniqueART.personid = tARTStartDate.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'LNMP'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Date of the first Day of LNMP' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tLNMPDate on tUniqueART.personid = tLNMPDate.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'EDD'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'EDD' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tEDDDate on tUniqueART.personid = tEDDDate.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_numeric as 'Gestationalage'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Gestation(Weeks)' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tGestationPeriod on tUniqueART.personid = tGestationPeriod.person_id
+left join
+(
+select t1.person_id , t1.concept_id , t1.value_numeric as 'weight',t1.date_created from obs t1
+where t1.date_created =
+(select MAX(t2.date_created) from obs t2 where t2.person_id = t1.person_id and t2.concept_id =
+(select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified')) and t1.concept_id =
+(select concept_id from concept_name where name = 'weight' and concept_name_type = 'fully_specified')
+and t1.date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+)tWeight on tUniqueART.personid = tWeight.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_numeric as 'muac'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'MUAC, Pregnancy Visit' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tMUAC on tUniqueART.personid = tMUAC.person_id
+left join (
+select obs.person_id,obs.concept_id,
+(case when obs.value_coded = 1 then 'Positive' else 'Negative' end) as 'TBStatus'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'TB Diagnosed?' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+) tTBDiagnosd on tUniqueART.personid = tTBDiagnosd.person_id
+left join
+(
+select person_id , concept_short_name as 'whostage' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id
+from obs inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'WHO Stage' and concept_name_type = 'Fully_specified') and obs.voided = 0 group by person_id
+)tOccupation
+)tWHOStage on tUniqueART.personid = tWHOStage.person_id
+left join
+(
+select t1.person_id , t1.concept_id , t1.value_numeric as 'cdfour',t1.date_created from obs t1
+where t1.date_created =
+(select MAX(t2.date_created) from obs t2 where t2.person_id = t1.person_id and t2.concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified')) and t1.concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'fully_specified')
+and t1.date_created between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')
+)tCdfour on tUniqueART.personid = tCdfour.person_id
+left join
+(
+select person_id , concept_short_name as 'partnerResult'
+ from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id
+from obs inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Result' and concept_name_type = 'Fully_specified') and obs.voided = 0 group by person_id
+)tOccupation
+)tHivResult on tUniqueART.personid = tHivResult.person_id
+LEFT JOIN
+(
+select obs.person_id,obs.concept_id,
+(case when obs.value_coded = 1 then 'YES' else 'NO' end) as 'Cotrimoxazole'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Cotrimoxazole/Dapsone' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+) tCotrimoxazole on tUniqueART.personid = tCotrimoxazole.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'tbrx'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Date Started TB RX' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tBrx on tUniqueART.personid = tBrx.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_text as 'tbRegNo'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'TB Unit Number' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tbRegNumber on tUniqueART.personid = tbRegNumber.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'dateVLSampleCollected'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Date VL Sample Collected?' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tDateVLCollected on tUniqueART.personid = tDateVLCollected.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_numeric as 'VLResults'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'VL Results' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tVLResults on tUniqueART.personid = tVLResults.person_id
+left join
+(
+select obs.person_id,obs.concept_id , obs.value_text as 'HeiNumber'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Unique ART No/HEI No' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tHeiNumber on tUniqueART.personid = tHeiNumber.person_id
+left join(
+select obs.person_id,obs.concept_id , obs.value_datetime as 'Date_Of_Delivery'
+from obs obs
+left join concept_name cn on obs.concept_id = cn.concept_id
+where cn.name = 'Post Natal,Date Of Delivery' and cn.concept_name_type = 'fully_specified' and obs.voided = 0 group by obs.person_id
+)tDateOfDelivery on tUniqueART.personid = tDateOfDelivery.person_id
+left join
+(
+select distinct(person_id) , concept_short_name as 'place_of_delivery' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Post Natal ,Place Delivery' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)placeofDelivery
+)tplaceofDelivery on tUniqueART.personid = tplaceofDelivery.person_id
+left join (
+select person_id , concat(coalesce(concat("State: ",address1) , "N/A"), " " ,coalesce(concat("Boma: ",address4), ""), " ",coalesce(concat("Village: ",address5) , ""))
+as Address from person_address where preferred = 1
+) tpatientAddrress on tUniqueART.personid = tpatientAddrress.person_id
+left join
+(
+select distinct(person_id) , concept_short_name as 'delivery_outcome' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Maternity card, Delivery Outcome' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)deliveryoutcome
+)tdeliveryoutcome on tUniqueART.personid = tdeliveryoutcome.person_id
+left join(
+select distinct(person_id),
+(case when value_coded = 1 then 'Yes' else 'No' end) as 'InfantReceivedProphylaxis'
+from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Infant Received ARV Prophylaxis at Birth' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)infantReceivedProphylaxis
+)tInfantReceivedProphylaxis on tUniqueART.personid = tInfantReceivedProphylaxis.person_id
+left join(
+select distinct(person_id) , concept_short_name as 'treatment_status' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Treatment Status' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)treatmentStatus
+)tTreatmentStatus on tUniqueART.personid = tTreatmentStatus.person_id
+left join(
+select distinct(person_id) , concept_short_name as 'Entry_to_PMTCT' from(
+select obs.person_id , obs.value_coded,concept_view.concept_short_name,obs.obs_id , obs.encounter_id
+from obs
+inner join (select person_id , concept_id , max(encounter_id) maxdate from obs group by person_id) b on obs.person_id = b.person_id and obs.encounter_id = b.maxdate
+inner join concept_view on obs.value_coded=concept_view.concept_id inner join concept on obs.concept_id=concept.concept_id
+where concept.concept_id= (select concept_id from concept_name where name = 'Entry to PMTCT' and concept_name_type = 'Fully_specified') and obs.voided = 0
+)entryTopmtct
+)tEntryTopmtct on tUniqueART.personid = tEntryTopmtct.person_id
+
+left join(
+select distinct(pid), firstregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)tfirstlinereg
+)tfirstlineregimen on tUniqueART.personid = tfirstlineregimen.pid
+left join (
+select distinct(pid), firstsubstitutionregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)tSubRegimen
+)tFirstSubstitituionregime on tUniqueART.personid = tFirstSubstitituionregime.pid
+left join (
+select distinct(pid), secondswitchwithinfirstline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondswitchwithinfirstline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)tsecoondfirstswithc
+)tSecondSubstitutionfirstline on tUniqueART.personid = tSecondSubstitutionfirstline.pid
+ left join (
+ select distinct(pid), secondlinefirst from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondlinefirst' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)secondlinefirst
+)tSecondlineoriginal on tUniqueART.personid = tSecondlineoriginal.pid
+left join (
+select distinct(pid), firstsubstitutionwithinsecond from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionwithinsecond' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)firstsubstitutionwithinsecond
+)tfirstsubstitutionwithinsecondline on tUniqueART.personid = tfirstsubstitutionwithinsecondline.pid
+left join (
+select distinct(pid), secondsubstitutionwithinsecondline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondsubstitutionwithinsecondline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)secondsubstitutionwithinsecondline
+)tsecondsubstitutionwithinsecondline on tUniqueART.personid = tsecondsubstitutionwithinsecondline.pid
+
diff --git a/openmrs/apps/reports/sql/artDispensingRegister.sql b/openmrs/apps/reports/sql/artDispensingRegister.sql
new file mode 100644
index 000000000..9fdaeec2b
--- /dev/null
+++ b/openmrs/apps/reports/sql/artDispensingRegister.sql
@@ -0,0 +1,32 @@
+select Unique_ART_Number as'Unique ART Number', Client_Name as 'Client Name' , mobileNumber as 'Client Contacts' , Sex , Age , Date , RegimenNames as 'Regimen / Quantity' , CTXDapsone as 'CTX / Dapsone' , OtherDrugs as 'Other Drugs' from (
+select o.patient_id, pa.value as 'Unique_ART_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), '', coalesce(family_name , '') )
+ as 'Client_Name',
+ gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age', o.date_created As Date,
+GROUP_CONCAT(case when c.uuid = '13382e01-9f18-488b-b2d2-58ab54c82d82' and o.date_created BETWEEN DATE_FORMAT('#startDate#' , '%Y-%m-01 00:00:00')
+AND DATE_FORMAT(LAST_DAY('#endDate#'), '%Y-%m-%d 23:59:59') then concat(dr.name," = (" , do.quantity , ") " , " " , cm.name) end) as RegimenNames,
+GROUP_CONCAT(case when c.uuid in ('e2acae74-9559-49b7-a5a7-36b633a5427d','9844649e-0411-4011-a1f8-4a0da4155c76','f8c61966-0a8a-425f-858c-93dfabc1c82c')
+and o.date_created BETWEEN DATE_FORMAT('#startDate#', '%Y-%m-01 00:00:00')
+AND DATE_FORMAT(LAST_DAY('#endDate#'), '%Y-%m-%d 23:59:59') then concat(dr.name, " = (" , do.quantity , ") " , " " , cm.name) end) as CTXDapsone,
+GROUP_CONCAT(case when c.uuid NOT IN ('13382e01-9f18-488b-b2d2-58ab54c82d82' , 'e2acae74-9559-49b7-a5a7-36b633a5427d',
+ '9844649e-0411-4011-a1f8-4a0da4155c76','f8c61966-0a8a-425f-858c-93dfabc1c82c')
+ and o.date_created BETWEEN DATE_FORMAT('#startDate#' , '%Y-%m-01 00:00:00')
+AND DATE_FORMAT(LAST_DAY('#endDate#'), '%Y-%m-%d 23:59:59') then concat(dr.name, " = (" , do.quantity , ") " , " " , cm.name) end) as OtherDrugs
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+inner JOIN orders as o on o.patient_id = pt.patient_id
+LEFT JOIN drug_order do on o.order_id = do.order_id
+INNER JOIN drug dr on o.concept_id = dr.concept_id
+LEFT JOIN concept_name as cm on cm.concept_id = do.quantity_units
+left join concept as c on dr.dosage_form = c.concept_id
+where pa.person_attribute_type_id = 29 and o.date_created >= '#startDate#' and o.date_created <= DATE_FORMAT(('#endDate#'), '%Y-%m-%d 23:59:59')
+group by o.patient_id
+)tt
+LEFT JOIN
+(
+select pa.person_id, pa.person_attribute_type_id , pa.value as 'mobileNumber' from person_attribute pa
+left join person_attribute_type pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+where pat.name = 'MobileNumber'
+)tMobile on tt.patient_id = tMobile.person_id
diff --git a/openmrs/apps/reports/sql/artMonthlyStartedOnArtReport.sql b/openmrs/apps/reports/sql/artMonthlyStartedOnArtReport.sql
new file mode 100644
index 000000000..c609be27d
--- /dev/null
+++ b/openmrs/apps/reports/sql/artMonthlyStartedOnArtReport.sql
@@ -0,0 +1,816 @@
+-- ART Monthly Report - New and cumulative number of persons started on ART
+
+
+
+select '<1 Yrs' as Title,
+count(distinct(case when pidd is not null and sex = 'M' and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+count(distinct(case when pidd is not null and sex = 'F' and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+count(distinct(case when pidd is not null and sex in ('F','M') and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+count(distinct(case when pidd is not null and sex = 'M' and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#','%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+count(distinct(case when pidd is not null and sex = 'F' and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#','%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+'N/A' as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+'N/A' as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+count(distinct(case when pidd is not null and sex in ('M','F') and ctxOrDapsonStartDate > DATE_FORMAT('#startDate#','%Y-%m-01') and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\nTotal',
+count(distinct(case when pidd is not null and sex = 'M' and ctxOrDapsonStartDate is not null and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nMale',
+count(distinct(case when pidd is not null and sex = 'F' and ctxOrDapsonStartDate is not null and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nFemale',
+count(distinct(case when pidd is not null and sex in ('F','M') and ctxOrDapsonStartDate is not null and ctxOrDapsonStartDate <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nTotal'
+from (
+select pa.person_id as pidd, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED')
+and TIMESTAMPDIFF(MONTH, p.birthdate, DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) <= 12
+)tDemographics
+inner join (
+select ctxOrDapsonStartDate , ctxDapsone_pid from (
+select person_id as ctxDapsone_pid, concept_id, value_datetime as 'ctxOrDapsonStartDate' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'CTX or Dapose Start Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pidd , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+ (select concept_id from concept_name where name = 'CTX or Dapose Start Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pidd) c on
+a.ctxDapsone_pid = c.pidd and a.encounter_id = c.maxdate
+)tCtxDapsonStartDate on tDemographics.pidd = tCtxDapsonStartDate.ctxDapsone_pid
+
+
+UNION ALL
+
+SELECT
+ '1-4 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 1 and 4 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '5-9 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 5 and 9 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '10-14 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '15-19 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '20-24 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '25-29 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '30-34 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '35-39 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '40-44 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '45-49 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '50-54 YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 54 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ '55+ YRS' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 AND TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) >= 55 and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Total' as 'Age Group',
+ count(maleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+ count(femaleGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+ count(totalGenderPreviousReportingPeriod) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+ count(maleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+ count(femaleGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+ count(pregnantWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+ count(breastFeedingWomens) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+ count(totalGenderCurrentReportingPeriod) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Total',
+ count(maleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Male',
+ count(femaleGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Female',
+ count(totalGenderSoFar) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+FROM (
+ SELECT
+ CASE WHEN (gender = 'M' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END maleGenderPreviousReportingPeriod,
+ CASE WHEN (gender = 'F' and MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END femaleGenderPreviousReportingPeriod,
+ CASE WHEN (MONTH(artStartDate) < MONTH(CURDATE())) THEN 1 END totalGenderPreviousReportingPeriod,
+ CASE WHEN (gender = 'M' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END maleGenderCurrentReportingPeriod,
+ CASE WHEN (gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END femaleGenderCurrentReportingPeriod,
+ CASE WHEN (pregnant = 1 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END pregnantWomens,
+ CASE WHEN (breastFeeding = 1 and gender = 'F' and MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END breastFeedingWomens,
+ CASE WHEN (MONTH(artStartDate) = MONTH(CURDATE()) AND YEAR(artStartDate) = YEAR(CURDATE())) THEN 1 END totalGenderCurrentReportingPeriod,
+ CASE WHEN (gender = 'M' and artStartDate is not NULL) THEN 1 END maleGenderSoFar,
+ CASE WHEN (gender = 'F' and artStartDate is not NULL) THEN 1 END femaleGenderSoFar,
+ CASE WHEN (artStartDate is not NULL and artStartDate is not NULL) THEN 1 END totalGenderSoFar
+ FROM person
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_datetime AS 'artStartDate' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS asd ON (asd.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'pregnant' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="FP Pregnant" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'breastFeeding' FROM obs o JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Currently Breastfeeding?" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS bf ON (bf.visitPatientId = person_id)
+) p
+union all
+select 'Total Number of Clients Taking CTX ',
+count(distinct(case when pid is not null and gender = 'M' and date_activated > DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#'- INTERVAL 1 MONTH,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+count(distinct(case when pid is not null and gender in ('M','F') and date_activated > DATE_FORMAT('#startDate#'- INTERVAL 1 MONTH,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#')- INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+count(distinct(case when pid is not null and gender = 'M' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) and edd > '#endDate#' then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) and isBreastfeeding is not null then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+count(distinct(case when pid is not null and gender in ('M','F') and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\nTotal',
+count(distinct(case when pidd is not null and sex = 'M' then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nMale',
+count(distinct(case when pidd is not null and sex = 'F' then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nFemale',
+count(distinct(case when pidd is not null and sex in ('F','M') then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+from (
+select person_id, arvreceivedbefore , gender from (
+select obs.person_id, obs.concept_id, obs.obs_datetime , obs.encounter_id , obs.value_coded as 'arvreceivedbefore', obs.voided, gender from obs obs
+left join person p on obs.person_id = p.person_id
+where obs.concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs.obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and obs.value_coded = 2 and obs.voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+ obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)newStartedARTs
+inner join(
+select distinct(pid), firstregimen , date_activated from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'CTX Drug' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+order by patient_id, date_activated) b where row_num = 1
+)tfirstlinereg
+)tnewStartedARTs on newStartedARTs.person_id = tnewStartedARTs.pid
+left join
+(
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIpregnant on newStartedARTs.person_id = tIpregnant.person_id
+left join (
+select person_id, edd from (
+select person_id, concept_id, obs_datetime as 'edd' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEdd on newStartedARTs.person_id = tEdd.person_id
+left join(
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tBreastfeeding on newStartedARTs.person_id = tBreastfeeding.person_id
+inner join (
+select person_id as pidd, arvreceivedbefore , gender as 'sex' from (
+select obs.person_id, obs.concept_id, obs.obs_datetime , obs.encounter_id , obs.value_coded as 'arvreceivedbefore', obs.voided, gender from obs obs
+left join person p on obs.person_id = p.person_id
+where obs.concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs.obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and obs.value_coded = 2 and obs.voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+ obs_datetime <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPersonsEverStartedCtx on tnewStartedARTs.pid = tPersonsEverStartedCtx.pidd
+union all
+select 'Total Number of Clients Taking Dapsone',
+count(distinct(case when pid is not null and gender = 'M' and date_activated > DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Male',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#'- INTERVAL 1 MONTH,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#') - INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Female',
+count(distinct(case when pid is not null and gender in ('M','F') and date_activated > DATE_FORMAT('#startDate#'- INTERVAL 1 MONTH,'%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#')- INTERVAL 1 MONTH,'%Y-%m-%d 23:59:59')) then pid end)) as 'Cumulative number of persons ever started on ART at this facility\nat the end of the previous reporting period\n Total',
+count(distinct(case when pid is not null and gender = 'M' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Male',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Female',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) and edd > '#endDate#' then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Pregnant',
+count(distinct(case when pid is not null and gender = 'F' and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) and isBreastfeeding is not null then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\n Breastfeeding',
+count(distinct(case when pid is not null and gender in ('M','F') and date_activated > DATE_FORMAT('#startDate#','%Y-%m-01') and date_activated <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) then pid end)) as 'New persons started on ART at this facility\nduring the reporting period (Month)\nTotal',
+count(distinct(case when pidd is not null and sex = 'M' then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nMale',
+count(distinct(case when pidd is not null and sex = 'F' then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\nFemale',
+count(distinct(case when pidd is not null and sex in ('F','M') then pidd end)) as 'Cumulative number of persons ever started on ART at this facility\nat end of the current reporting period (Month)\n Total'
+from (
+select person_id, arvreceivedbefore , gender from (
+select obs.person_id, obs.concept_id, obs.obs_datetime , obs.encounter_id , obs.value_coded as 'arvreceivedbefore', obs.voided, gender from obs obs
+left join person p on obs.person_id = p.person_id
+where obs.concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs.obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and obs.value_coded = 2 and obs.voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+ obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)newStartedARTs
+inner join(
+select distinct(pid), firstregimen , date_activated from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'Dapsone Drugs' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+order by patient_id, date_activated) b where row_num = 1
+)tfirstlinereg
+)tnewStartedARTs on newStartedARTs.person_id = tnewStartedARTs.pid
+left join
+(
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIpregnant on newStartedARTs.person_id = tIpregnant.person_id
+left join (
+select person_id, edd from (
+select person_id, concept_id, obs_datetime as 'edd' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEdd on newStartedARTs.person_id = tEdd.person_id
+left join(
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT('#endDate#','%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tBreastfeeding on newStartedARTs.person_id = tBreastfeeding.person_id
+inner join (
+select person_id as pidd, arvreceivedbefore , gender as 'sex' from (
+select obs.person_id, obs.concept_id, obs.obs_datetime , obs.encounter_id , obs.value_coded as 'arvreceivedbefore', obs.voided, gender from obs obs
+left join person p on obs.person_id = p.person_id
+where obs.concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs.obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and obs.value_coded = 2 and obs.voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+ obs_datetime <= (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59')) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPersonsEverStartedCtx on tnewStartedARTs.pid = tPersonsEverStartedCtx.pidd
+
+
+
+
+
+
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/artRegister.sql b/openmrs/apps/reports/sql/artRegister.sql
new file mode 100644
index 000000000..39252cbb2
--- /dev/null
+++ b/openmrs/apps/reports/sql/artRegister.sql
@@ -0,0 +1,530 @@
+select artnumber as 'Unique ART Number' , datestartedart as 'ART Start Date',
+(case when HIV_Retesting_for_ART_initiation is not null then '1' else '0' end) as 'HIV Retesting for ART initiation. 0=No 1=Yes',
+ ClientName as 'Name in Full' , mobile as "Client's Address - Mobile" , occupation as 'Occupation', '' as 'Key Population', muac as 'Mid Upper Arm Conference', Age as 'Age (years)', sex as 'Sex (M or F)',
+WEIGHT as 'Weight (kg)' , HEIGHT as 'Height /Length for Child < 2 years (cm)', BMI as 'Body Mass Index (BMI) (kg/mSq)', whostage as 'WHO clinical stage',
+CD4 as 'CD4 count or (if child <5 years indicate CD4%)', dateStartedCTXorDapsone as 'CTX or Dapsone start month/year' ,
+isoniazidStartDate1 as 'INH Prophylaxis - Date\n 1', isoniazidStartDate2 as 'INH Prophylaxis - Date\n 2' , isoniazidStartDate3 as 'INH Prophylaxis - Date\n 3' , isoniazidStartDate4 as 'INH Prophylaxis - Date\n 4',isoniazidStartDate5 as 'INH Prophylaxis - Date\n 5', isoniazidStartDate6 as 'INH Prophylaxis - Date\n 6' ,
+date_started_tbrx as 'TB RX start Month/year and TB reg No.', Pregnancy1 as 'Pregnancy\n1' , Pregnancy2 as 'Pregnancy\n2',Pregnancy3 as 'Pregnancy\n3' , Pregnancy4 as 'Pregnancy\n4' ,
+(case when currently_breastfeeding = 'YES' then '1' else '0' end) as 'Breastfeeding (0=No; 1=Yes; 2=N/A)',
+firstregimen as '1st Line Regimen - Original Regimen', firstsubstitutionregimen as '1st Line Regimen - 1st: Substitution drug code' , secondswitchwithinfirstline as '1st Line Regimen - 2nd: Substitution drug code' , secondlinefirst as '2nd Line Regimen - 2nd Line Regimen switched to',
+firstsubstitutionwithinsecond as '2nd Line Regimen - 1st: Substitution drug code',
+secondsubstitutionwithinsecondline as '2nd Line Regimen - 2nd: Substitution drug code' , tchildfirstregimen as 'Child 1st Line Regimens' , tChildSecondLine as 'Child 2nd Line Regimens'
+ from (
+select patient_id, min(date_created) as datestartedart
+from (
+select o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)a group by patient_id
+)tDateStartedArt inner join
+(
+select * from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type
+where name = 'TypeofPatient'
+) and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+)tNewPatientDemographics on tDateStartedArt.patient_id = tNewPatientDemographics.pid
+left join (
+select pn.person_id as 'pid', pn.given_name, pn.middle_name, pa.value as 'mobile' from person_name pn
+left join person_attribute pa on pn.person_id = pa.person_id where pa.person_attribute_type_id
+=(select person_attribute_type_id from person_attribute_type where name = 'MobileNumber')
+)tMobile on tNewPatientDemographics.pid = tMobile.pid
+left join (
+select * from (
+select person_id, concept_id, value_datetime as 'HIV_Retesting_for_ART_initiation' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date of HIV Retesting Before ART' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateRestedHivbeforeARTinit on tNewPatientDemographics.pid = tDateRestedHivbeforeARTinit.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'HEIGHT',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEIGHT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEIGHT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHeight on tNewPatientDemographics.pid = tHeight.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'WEIGHT',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'WEIGHT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'WEIGHT' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tWeight on tNewPatientDemographics.pid = tWeight.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'BMI',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'BMI' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'BMI' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tBMI on tNewPatientDemographics.pid = tBMI.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'CD4',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'CD4' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCDFour on tNewPatientDemographics.pid = tCDFour.person_id
+left join(
+select * from (
+select person_id, concept_id, value_datetime as 'date_started_tbrx' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+ (select concept_id from concept_name where name = 'Date Started TB RX' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDatestartedtbrx on tNewPatientDemographics.pid = tDatestartedtbrx.person_id
+left join(
+select pid , tConceptname.name as 'whostage' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'WHO Stage' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'WHO Stage' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tWhoStage on tNewPatientDemographics.pid = tWhoStage.pid
+left join(
+select pid, min(date_created) as dateStartedCTXorDapsone
+from (
+select o.patient_id as pid, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form in (
+(select concept_id from concept_name where name = 'CTX Drug' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0),
+(select concept_id from concept_name where name = 'Dapsone Drugs' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+)
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)a group by pid
+)tDateStartedCTxorDapsone on tNewPatientDemographics.pid = tDateStartedCTxorDapsone.pid
+left join (
+select person_id ,
+(case when value_coded = 1 then 'Yes' else 'No' end) as 'currently_breastfeeding'
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCurrentlyBreastfeeeding on tNewPatientDemographics.pid = tCurrentlyBreastfeeeding.person_id
+left join(
+select distinct(pid), firstregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)tfirstlinereg
+)tfirstlineregimen on tNewPatientDemographics.pid = tfirstlineregimen.pid
+left join (
+select distinct(pid), firstsubstitutionregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)tSubRegimen
+)tFirstSubstitituionregime on tNewPatientDemographics.pid = tFirstSubstitituionregime.pid
+left join (
+select distinct(pid), secondswitchwithinfirstline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondswitchwithinfirstline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)tsecoondfirstswithc
+)tSecondSubstitutionfirstline on tNewPatientDemographics.pid = tSecondSubstitutionfirstline.pid
+ left join (
+ select distinct(pid), secondlinefirst from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondlinefirst' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)secondlinefirst
+)tSecondlineoriginal on tNewPatientDemographics.pid = tSecondlineoriginal.pid
+left join (
+select distinct(pid), firstsubstitutionwithinsecond from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'firstsubstitutionwithinsecond' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 2
+)firstsubstitutionwithinsecond
+)tfirstsubstitutionwithinsecondline on tNewPatientDemographics.pid = tfirstsubstitutionwithinsecondline.pid
+left join (
+select distinct(pid), secondsubstitutionwithinsecondline from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'secondsubstitutionwithinsecondline' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 3
+)secondsubstitutionwithinsecondline
+)tsecondsubstitutionwithinsecondline on tNewPatientDemographics.pid = tsecondsubstitutionwithinsecondline.pid
+left join (
+select distinct(pid), tchildfirstregimen from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'tchildfirstregimen' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)childfirstregimen
+)tChildfirstregimen on tNewPatientDemographics.pid = tChildfirstregimen.pid
+left join (
+select distinct(pid), tChildSecondLine from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'tChildSecondLine' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and dr.name in ('5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL','5c = ABC/3TC (120/60) + RAL' , '5d = AZT/3TC +ATV/r' , '5e = ABC/3TC + ATV/r' , '5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*' , '5i = ABC/3TC +LPV/r')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b where row_num = 1
+)tChildSecondLine
+)tChildSecondLineRegimen on tNewPatientDemographics.pid = tChildSecondLineRegimen.pid
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate1' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 1
+)tIsoniazidDate1 on tNewPatientDemographics.pid = tIsoniazidDate1.patient_id
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate2' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 2
+)tIsoniazidDate2 on tNewPatientDemographics.pid = tIsoniazidDate2.patient_id
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate3' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 3
+)tIsoniazidDate3 on tNewPatientDemographics.pid = tIsoniazidDate3.patient_id
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate4' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 4
+)tIsoniazidDate4 on tNewPatientDemographics.pid = tIsoniazidDate4.patient_id
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate5' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 5
+)tIsoniazidDate5 on tNewPatientDemographics.pid = tIsoniazidDate5.patient_id
+left join (
+select @row_num := 0 , row_num, patient_id ,date_activated as 'isoniazidStartDate6' from (
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , date_activated ,
+date_created , patient_id , @prev_value:=patient_id, @prev_drugId:= concept_id from orders
+where concept_id = (select concept_id from concept_name where name = 'Isoniazid' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and date_activated <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tIoniziad where row_num = 6
+)tIsoniazidDate6 on tNewPatientDemographics.pid = tIsoniazidDate6.patient_id
+left join(
+select pid , tConceptname.name as 'occupation' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Occupation' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Occupation' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tOccupation on tNewPatientDemographics.pid = tOccupation.pid
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'muac',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'MUAC, Pregnancy Visit' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'MUAC, Pregnancy Visit' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMuac on tNewPatientDemographics.pid = tMuac.person_id
+left join(
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIpregnant on tNewPatientDemographics.pid = tIpregnant.person_id
+left join (
+select pidd ,
+(case when TIMESTAMPDIFF(MONTH, date_activated, PregnancyOneEdd) <= 9 then 'YM' else 'N/A' end) as 'Pregnancy1' from (
+select distinct(patient_id) as pidd,row_num, date_activated , name as 'firstregimen' , PregnancyOneEdd from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided ,
+o.date_activated , o.date_created , PregnancyOneEdd
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join (
+select person_id as pid ,
+(case when row_num = 1 then pregnancyOneEdd else 'N/A' end ) as 'PregnancyOneEdd' from (
+select @row_num := 0 , row_num, person_id ,obs_datetime as 'obscreateddate' , obs_group_id , obs_group1 ,pregnancyOneEdd from (
+select @row_num :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id from obs
+where concept_id = (select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPregnancies
+inner join (
+select @row_nm := 0 , row_nm, person_id as pid ,obs_datetime as 'obsdatetime' , obs_group_id as 'obs_group1' ,
+value_datetime as 'pregnancyOneEdd' from (
+select @row_nm :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_nm+1, 1) AS row_nm,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id , value_datetime from obs
+where concept_id = (select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)EDD
+)tPregnancyEDD on tPregnancies.obs_group_id = tPregnancyEDD.obs_group1
+)tt where row_num = 1
+)ss on o.patient_id = ss.pid
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b
+)tfirstlinereg where date_activated < PregnancyOneEdd and TIMESTAMPDIFF(MONTH, date_activated, PregnancyOneEdd) <= 9 group by pidd
+)tPregrancyOne on tNewPatientDemographics.pid = tPregrancyOne.pidd
+left join (
+
+select pidd ,
+(case when TIMESTAMPDIFF(MONTH, date_activated, PregnancyTwoEdd) <= 9 then 'YM' else 'N/A' end) as 'Pregnancy2' from (
+select distinct(patient_id) as pidd,row_num, date_activated , name as 'firstregimen' , PregnancyTwoEdd from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided ,
+o.date_activated , o.date_created , PregnancyTwoEdd
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join (
+select person_id as pid ,
+(case when row_num = 2 then pregnancyTwoEdd else 'N/A' end ) as 'PregnancyTwoEdd' from (
+select @row_num := 0 , row_num, person_id ,obs_datetime as 'obscreateddate' , obs_group_id , obs_group1 ,pregnancyTwoEdd from (
+select @row_num :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id from obs
+where concept_id = (select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPregnancies
+inner join (
+select @row_nm := 0 , row_nm, person_id as pid ,obs_datetime as 'obsdatetime' , obs_group_id as 'obs_group1' ,
+value_datetime as 'pregnancyTwoEdd' from (
+select @row_nm :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_nm+1, 1) AS row_nm,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id , value_datetime from obs
+where concept_id = (select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)EDD
+)tPregnancyEDD on tPregnancies.obs_group_id = tPregnancyEDD.obs_group1
+)tt where row_num = 2
+)ss on o.patient_id = ss.pid
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b
+)tfirstlinereg where date_activated < PregnancyTwoEdd and TIMESTAMPDIFF(MONTH, date_activated, PregnancyTwoEdd) <= 9 group by pidd
+)tPregnancyTwo on tNewPatientDemographics.pid = tPregnancyTwo.pidd
+left join (
+
+select pidd ,
+(case when TIMESTAMPDIFF(MONTH, date_activated, PregnancyThreeEdd) <= 9 then 'YM' else 'N/A' end) as 'Pregnancy3' from (
+select distinct(patient_id) as pidd,row_num, date_activated , name as 'firstregimen' , PregnancyThreeEdd from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided ,
+o.date_activated , o.date_created , PregnancyThreeEdd
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join (
+select person_id as pid ,
+(case when row_num = 3 then PregnancyThreeEdd else 'N/A' end ) as 'PregnancyThreeEdd' from (
+select @row_num := 0 , row_num, person_id ,obs_datetime as 'obscreateddate' , obs_group_id , obs_group1 ,PregnancyThreeEdd from (
+select @row_num :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id from obs
+where concept_id = (select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPregnancies
+inner join (
+select @row_nm := 0 , row_nm, person_id as pid ,obs_datetime as 'obsdatetime' , obs_group_id as 'obs_group1' ,
+value_datetime as 'PregnancyThreeEdd' from (
+select @row_nm :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_nm+1, 1) AS row_nm,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id , value_datetime from obs
+where concept_id = (select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)EDD
+)tPregnancyEDD on tPregnancies.obs_group_id = tPregnancyEDD.obs_group1
+)tt where row_num = 3
+)ss on o.patient_id = ss.pid
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b
+)tfirstlinereg where date_activated < PregnancyThreeEdd and TIMESTAMPDIFF(MONTH, date_activated, PregnancyThreeEdd) <= 9 group by pidd
+)tPregnancyThree on tNewPatientDemographics.pid = tPregnancyThree.pidd
+left join (
+
+select pidd ,
+(case when TIMESTAMPDIFF(MONTH, date_activated, PregnancyFourEdd) <= 9 then 'YM' else 'N/A' end) as 'Pregnancy4' from (
+select distinct(patient_id) as pidd,row_num, date_activated , name as 'firstregimen' , PregnancyFourEdd from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided ,
+o.date_activated , o.date_created , PregnancyFourEdd
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+left join (
+select person_id as pid ,
+(case when row_num = 4 then PregnancyFourEdd else 'N/A' end ) as 'PregnancyFourEdd' from (
+select @row_num := 0 , row_num, person_id ,obs_datetime as 'obscreateddate' , obs_group_id , obs_group1 ,PregnancyFourEdd from (
+select @row_num :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_num+1, 1) AS row_num,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id from obs
+where concept_id = (select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tPregnancies
+inner join (
+select @row_nm := 0 , row_nm, person_id as pid ,obs_datetime as 'obsdatetime' , obs_group_id as 'obs_group1' ,
+value_datetime as 'PregnancyFourEdd' from (
+select @row_nm :=IF(@prev_value=person_id and @prev_drugId = concept_id ,@row_nm+1, 1) AS row_nm,
+concept_id , voided , person_id , obs_datetime ,
+date_created , @prev_value:=person_id, @prev_drugId:= concept_id , obs_group_id , value_datetime from obs
+where concept_id = (select concept_id from concept_name where name = 'EDD' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)EDD
+)tPregnancyEDD on tPregnancies.obs_group_id = tPregnancyEDD.obs_group1
+)tt where row_num = 4
+)ss on o.patient_id = ss.pid
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+and o.date_created <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+order by patient_id, date_activated) b
+)tfirstlinereg where date_activated < PregnancyFourEdd and TIMESTAMPDIFF(MONTH, date_activated, PregnancyFourEdd) <= 9 group by pidd
+)tPregnancyFour on tNewPatientDemographics.pid = tPregnancyFour.pidd
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/openmrs/apps/reports/sql/contactsNotTested.sql b/openmrs/apps/reports/sql/contactsNotTested.sql
new file mode 100644
index 000000000..11b31495e
--- /dev/null
+++ b/openmrs/apps/reports/sql/contactsNotTested.sql
@@ -0,0 +1,98 @@
+select ClientName as 'Index Name' , artnumber as 'ART Number' , Names as 'Contact Name' ,PhoneNumber as 'Contact Phone Number' from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+sexual_partner as 'Sexual Partner',
+(case when sexual_partner = 'YES' then sexual_partner_phone_number else family_member_phonenumber end) as 'PhoneNumber',
+(case when sexual_partner = 'YES' then sexualPartnerContacted else familyMemberContacted end) as 'wasContacted',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_phonenumber'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member,Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberMobile on tSexualRelationship.obs_group_id = tFamilyMemberMobile.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_phone_number'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner, Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerPhoneNumber on tSexualRelationship.obs_group_id = tSexualPartnerPhoneNumber.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerContacted on tSexualRelationship.obs_group_id = tSexualPartnerContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberContacted on tSexualRelationship.obs_group_id = tFamilyMemberContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid where wasContacted = 'NO'
+
+
+
+
diff --git a/openmrs/apps/reports/sql/contactsTested.sql b/openmrs/apps/reports/sql/contactsTested.sql
new file mode 100644
index 000000000..e0299a35e
--- /dev/null
+++ b/openmrs/apps/reports/sql/contactsTested.sql
@@ -0,0 +1,98 @@
+select ClientName as 'Index Name' , artnumber as 'ART Number' , Names as 'Contact Name' ,PhoneNumber as 'Contact Phone Number' from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+sexual_partner as 'Sexual Partner',
+(case when sexual_partner = 'YES' then sexual_partner_phone_number else family_member_phonenumber end) as 'PhoneNumber',
+(case when sexual_partner = 'YES' then sexualPartnerContacted else familyMemberContacted end) as 'wasContacted',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_phonenumber'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member,Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberMobile on tSexualRelationship.obs_group_id = tFamilyMemberMobile.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_phone_number'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner, Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerPhoneNumber on tSexualRelationship.obs_group_id = tSexualPartnerPhoneNumber.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerContacted on tSexualRelationship.obs_group_id = tSexualPartnerContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberContacted on tSexualRelationship.obs_group_id = tFamilyMemberContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid where wasContacted = 'YES'
+
+
+
+
diff --git a/openmrs/apps/reports/sql/currentOnARTThisMonth.sql b/openmrs/apps/reports/sql/currentOnARTThisMonth.sql
new file mode 100644
index 000000000..98c70b7ad
--- /dev/null
+++ b/openmrs/apps/reports/sql/currentOnARTThisMonth.sql
@@ -0,0 +1,96 @@
+select 'Total' as 'Adult 1st Line Regimens',
+count(distinct(case when patient_id is not null and name = '1a = AZT/3TC+EFV' then patient_id end)) as '1a = AZT/3TC+EFV',
+count(distinct(case when patient_id is not null and name = '1b = AZT/3TC/NVP' then patient_id end)) as '1b = AZT/3TC/NVP',
+count(distinct(case when patient_id is not null and name = '1f = TDF/3TC+EFV' then patient_id end)) as '1f = TDF/3TC+EFV',
+count(distinct(case when patient_id is not null and name = '1g = TDF/3TC+NVP' then patient_id end)) as '1g = TDF/3TC+NVP',
+count(distinct(case when patient_id is not null and name = '1h = TDF/FTC/EFV' then patient_id end)) as '1h = TDF/FTC/EFV',
+count(distinct(case when patient_id is not null and name = '1j = TDF/3TC+NVP' then patient_id end)) as '1J = TDF+FTC+NVP ',
+null as 'N/A',null as 'N/A'
+ from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate
+union all
+select null, null , null ,null ,null ,null, null,null,null
+union all
+select 'Adult 2nd Line Regimens', '2c=TDF+3TC+LPV/r' , '2d=TDF/3TC+ATV/r' ,'2e=TDF/FTC-LPV/r' ,'2f=TDF/FTC-ATV/r' ,'2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r'
+union all
+select 'Total' as 'Adult 2nd Line Regimens',
+count(distinct(case when patient_id is not null and name = '2c=TDF+3TC+LPV/r' then patient_id end)) as '2c=TDF+3TC+LPV/r',
+count(distinct(case when patient_id is not null and name = '2d=TDF/3TC+ATV/r' then patient_id end)) as '2d=TDF/3TC+ATV/r',
+count(distinct(case when patient_id is not null and name = '2e=TDF/FTC-LPV/r' then patient_id end)) as '2e=TDF/FTC-LPV/r',
+count(distinct(case when patient_id is not null and name = '2f=TDF/FTC-ATV/r' then patient_id end)) as '2f=TDF/FTC-ATV/r',
+count(distinct(case when patient_id is not null and name = '2g=AZT/3TC+LPV/r' then patient_id end)) as '2g=AZT/3TC+LPV/r',
+count(distinct(case when patient_id is not null and name = '2h=AZT/3TC+ATV/r' then patient_id end)) as '2h=AZT/3TC+ATV/r',
+count(distinct(case when patient_id is not null and name = '2i=ABC/3TC+LPV/r' then patient_id end)) as '2i=ABC/3TC+LPV/r',
+count(distinct(case when patient_id is not null and name = '2j=ABC/3TC+ATV/r'then patient_id end)) as '2j=ABC/3TC+ATV/r'
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate
+union all
+select null, null , null ,null ,null ,null, null,null,null
+union all
+select 'Child 1st Line Regimens', '4a = AZT/3TC+NVP' , '4b = AZT/3TC +EFV' ,'4f = ABC/3TC +NVP' ,'4g = TDF/3TC (120/60) + EFV (200mg)' ,'4h = TDF/FTC/EFV', '4i = ABC/3TC +LPV/r',null,null
+union all
+select 'Total' as 'Adult 1st Line Regimens',
+count(distinct(case when patient_id is not null and name = '4a = AZT/3TC+NVP' then patient_id end)) as '4a = AZT/3TC+NVP',
+count(distinct(case when patient_id is not null and name = '4b = AZT/3TC +EFV' then patient_id end)) as '4b = AZT/3TC +EFV',
+count(distinct(case when patient_id is not null and name = '4f = ABC/3TC +NVP' then patient_id end)) as '4f = ABC/3TC +NVP',
+count(distinct(case when patient_id is not null and name = '4g = TDF/3TC (120/60) + EFV (200mg)' then patient_id end)) as '4g = TDF/3TC (120/60) + EFV (200mg)',
+count(distinct(case when patient_id is not null and name = '4h = TDF/FTC/EFV' then patient_id end)) as '4h = TDF/FTC/EFV',
+count(distinct(case when patient_id is not null and name = '4i = ABC/3TC +LPV/r' then patient_id end)) as '4i = ABC/3TC +LPV/r',
+null,null
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name in ('4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate
+union all
+select null, null , null ,null ,null ,null, null,null,null
+union all
+select 'Child 2nd Line Regimens', '5b = AZT/3TC +RAL' , '5c = ABC/3TC (120/60) + RAL' ,'5d = AZT/3TC +ATV/r' ,'5e = ABC/3TC + ATV/r' ,'5f = TDF/3TC + ATV/r',null,null,null
+union all
+select 'Total' as 'Child 2nd Line Regimens',
+count(distinct(case when patient_id is not null and name = '5b = AZT/3TC +RAL' then patient_id end)) as '5b = AZT/3TC +RAL',
+count(distinct(case when patient_id is not null and name = '5c = ABC/3TC (120/60) + RAL' then patient_id end)) as '5c = ABC/3TC (120/60) + RAL',
+count(distinct(case when patient_id is not null and name = '5d = AZT/3TC +ATV/r' then patient_id end)) as '5d = AZT/3TC +ATV/r',
+count(distinct(case when patient_id is not null and name = '5e = ABC/3TC + ATV/r' then patient_id end)) as '5e = ABC/3TC + ATV/r',
+count(distinct(case when patient_id is not null and name = '5f = TDF/3TC + ATV/r' then patient_id end)) as '5f = TDF/3TC + ATV/r',
+null,null,null
+from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#','%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'))
+and name in ('5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL','5c = ABC/3TC (120/60) + RAL' , '5d = AZT/3TC +ATV/r' , '5e = ABC/3TC + ATV/r' , '5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*' , '5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate
+
+
diff --git a/openmrs/apps/reports/sql/currentOnArtLastMonth.sql b/openmrs/apps/reports/sql/currentOnArtLastMonth.sql
new file mode 100644
index 000000000..61c8ef599
--- /dev/null
+++ b/openmrs/apps/reports/sql/currentOnArtLastMonth.sql
@@ -0,0 +1,835 @@
+select '<1 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age < 1 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age < 1 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age < 1 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '1-4 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 1 and age < 5 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 1 and age < 5 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 1 and age < 5 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '5-9 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >=5 and age < 10 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 5 and age < 10 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 5 and age < 10 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '10-14 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 10 and age < 15 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 10 and age < 15 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 10 and age < 15 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '15-19 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 19 and age < 20 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 19 and age < 20 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 19 and age < 20 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '20-24 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 20 and age < 25 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 20 and age < 25 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 20 and age < 25 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '25-29 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 25 and age < 30 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 25 and age < 30 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 25 and age < 30 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '30-34 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 30 and age < 35 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 30 and age < 35 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 30 and age < 35 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '35-39 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 35 and age < 40 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 35 and age < 40 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 35 and age < 40 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '40-44 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 40 and age < 45 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 40 and age < 45 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 40 and age < 45 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '45-49 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 45 and age < 50 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 45 and age < 50 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 45 and age < 50 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '50+ YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 50 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 50 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 50 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select 'Total adults and children on 1st-line regimens' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select null , null , null , null
+union all
+select "On 2nd-line ARV regimen", null , null , null
+union all
+select '<1 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age < 1 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age < 1 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age < 1 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '1-4 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 1 and age < 5 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 1 and age < 5 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 1 and age < 5 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '5-9 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >=5 and age < 10 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 5 and age < 10 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 5 and age < 10 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '10-14 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 10 and age < 15 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 10 and age < 15 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 10 and age < 15 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '15-19 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 19 and age < 20 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 19 and age < 20 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 19 and age < 20 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '20-24 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 20 and age < 25 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 20 and age < 25 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 20 and age < 25 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '25-29 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 25 and age < 30 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 25 and age < 30 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 25 and age < 30 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '30-34 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 30 and age < 35 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 30 and age < 35 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 30 and age < 35 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '35-39 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 35 and age < 40 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 35 and age < 40 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 35 and age < 40 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '40-44 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 40 and age < 45 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 40 and age < 45 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 40 and age < 45 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '45-49 YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 45 and age < 50 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 45 and age < 50 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 45 and age < 50 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select '50+ YRS' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' and age >= 50 then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' and age >= 50 then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') and age >= 50 then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select 'Total adults and children on 2nd-line regimens' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+union all
+select 'Total current on ART\n(Adults and children on 1st & 2nd-line regimens)' as 'ARV regimen at end of Last Month',
+count(distinct(case when person_id is not null and sex = 'M' then person_id end)) as 'Male',
+count(distinct(case when person_id is not null and sex = 'F' then person_id end)) as 'Female',
+count(distinct(case when person_id is not null and sex in ('M','F') then person_id end)) as 'Total'
+from (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics inner join (
+select patient_id as pat_id from (
+select o.patient_id , o.concept_id , o.date_activated , o.voided , o.encounter_id , dr.name , o.date_stopped
+from orders o
+inner join drug dr on o.concept_id = dr.concept_id
+where o.date_stopped is null and order_reason_non_coded is null
+and date_activated between DATE_FORMAT('#startDate#' - INTERVAL 1 MONTH ,'%Y-%m-01') and (DATE_FORMAT(LAST_DAY('#startDate#' - INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59'))
+and name in ('2a=AZT/3TC+DTG','2b=ABC/3TC+DTG','2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r','2h=AZT/3TC+ATV/r',
+'2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG','5a = AZT/3TC+LPV/r','5b = AZT/3TC +RAL',
+'5c = ABC/3TC (120/60) + RAL','5d = AZT/3TC +ATV/r','5e = ABC/3TC + ATV/r','5f = TDF/3TC + ATV/r',
+'5g = AZT/3TC +DTG','5h = ABC/3TC + DTG*','5i = ABC/3TC +LPV/r','1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV', '4a = AZT/3TC+NVP','4b = AZT/3TC +EFV','4c = TDF/3TC (120/60) + LPV/r','4d = ABC/3TC (120/60) +DTG',
+'4f = ABC/3TC +NVP','4g = TDF/3TC (120/60) + EFV (200mg)','4h = TDF/FTC/EFV','4i = ABC/3TC +LPV/r','4J = AZT/3TC (60/30)+LPV/r',
+'4k = TDF/3TC+NVP','4i = ABC/3TC +AZT','ABC/3TC+LPV/r','ABC/3TC+DTG','TDF/3TC/DTG','AZT+NVP','AZT+3TC+LPV/r','AZT+3TC+NVP','ABC+3TC+LPV/r','ABC+3TC+EFV','AZT+3TC+RAL',
+'ABC+3TC+RAL','AZT+3TC+EFV','ABC+3TC+DTG','AZT+ 3TC+EFV','TDF+3TC+DTG','AZT/3TC+EFV','ABC/3TC AZT','ABC/3TC+LPV/r+RTV',
+'ABC/3TC+double dose DTG*','ABC/3TC+EFV','ABC/3TC+AZT')
+)a inner join ( select patient_id as pid, concept_id as cid, max(date_activated) maxdate from orders
+where date_stopped is null
+group by pid ) c on a.patient_id = c.pid and a.date_activated = c.maxdate group by pat_id
+)tCurrentFirstLineRegimen on tDemographics.person_id = tCurrentFirstLineRegimen.pat_id
+
+
+
+
diff --git a/openmrs/apps/reports/sql/highViralloadReport.sql b/openmrs/apps/reports/sql/highViralloadReport.sql
new file mode 100644
index 000000000..0f00d3d0d
--- /dev/null
+++ b/openmrs/apps/reports/sql/highViralloadReport.sql
@@ -0,0 +1,183 @@
+select @a:=@a+1 as 'Serial Number' , registrationDate as 'Date of registration', artnumber as 'ART Number', ClientName as 'Client FullNames' , value as 'Client Contacts',Age,sex as 'Sex (M/F)', dateSampleCollected as 'First Viral Load\nDate of sample collection',dateSampleReceived as 'First Viral Load\nDate of arrival of the result' ,
+vlresults as 'First Viral Load\nResult (Copies/ml)', firstEacDate as 'First EAC session - Date' , secondEacDate as 'Second EAC session - Date' , thirdEacDate as 'Third EAC session - Date', adherenceafterEac as 'Classification of adherence after EAC\n(Good, Fair, Poor)',
+repeatViralSampleCollectionDate as 'Repeat Viral Load\nDate of sample collection' , rvDateOfArrival as 'Repeat Viral Load\nDate of arrival of the result', adherencefailure as 'Repeat Viral Load\nResult (copies/ml)', outcomeAfterRepeat as 'Outcome\nVS:Viral Suppression (<1000copies/ml)\nSTF:Suspecion of Treatment Failure(≥1000copies/ml)',
+(case when regimenchangedto is not null then 'Y' else 'N' end) as ' Was regimen switched? (Y/N)',
+date_activated as 'Date decision made to\nChange ART regimen' , (case when mdtHeld = 'True' then 'Y' else 'N' end) as 'MDT held? (Y/N)' , mdtChangeDate as 'MDT Held - Date' ,date_activated as 'Actual regimen\n change date (DD/MM/YYYY)',
+(case when regimenchangedto is not null and date_activated is not null and date_activated < repeatViralSampleCollectionDate THEN repeatViralSampleCollectionDate else 'N/A' end) as 'Repeat Viral Load after\nRegimen Change\nDate of sample collection',
+(case when regimenchangedto is not null and date_activated is not null and date_activated < rvDateOfArrival THEN rvDateOfArrival else 'N/A' end) as 'Repeat Viral Load after\nRegimen Change\nDate of arrival of the result',
+(case when regimenchangedto is not null and date_activated is not null and date_activated < adherencefailuredate THEN adherencefailuredate else 'N/A' end) as 'Repeat Viral Load after\nRegimen Change\nResult (copies/ml)',
+summary as 'Comments'
+from (
+select (SELECT @a:= 0) AS a , obs_datetime as 'registrationDate', person_id , vlresults from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'vlresults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate and vlresults >= 1000
+)tVlloadAbove100
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tVlloadAbove100.person_id = tDemographics.person_id
+left join(
+select pa.person_id, pa.person_attribute_type_id , pa.value from person_attribute pa
+left join person_attribute_type pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+where pat.name = 'MobileNumber'
+)tMobileNumber on tVlloadAbove100.person_id = tMobileNumber.person_id
+left join(
+select person_id , dateSampleCollected from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dateSampleCollected', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date VL Sample Collected?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date VL Sample Collected?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateSampleCollected on tVlloadAbove100.person_id = tDateSampleCollected.person_id
+left join (
+select person_id , dateSampleReceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dateSampleReceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Sample Received at Testing Lab' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Sample Received at Testing Lab' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateSampleReceived on tVlloadAbove100.person_id = tDateSampleReceived.person_id
+left join(
+select person_id , firstEacDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'firstEacDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'First EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'First EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFirstEacDate on tVlloadAbove100.person_id = tFirstEacDate.person_id
+left join(
+select person_id , secondEacDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'secondEacDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Second EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Second EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSecondEacDate on tVlloadAbove100.person_id = tSecondEacDate.person_id
+left join(
+select person_id , thirdEacDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'thirdEacDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Third EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Third EAC Session Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tThirdEacDate on tVlloadAbove100.person_id = tThirdEacDate.person_id
+left join (
+select pid , tConceptname.name as 'adherenceafterEac' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Classification Of Adherence After EAC' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Classification Of Adherence After EAC' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tClassificationOfAdherence on tVlloadAbove100.person_id = tClassificationOfAdherence.pid
+left join(
+select person_id , repeatViralSampleCollectionDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'repeatViralSampleCollectionDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Sample Collection Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Sample Collection Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tRvDateOfCollection on tVlloadAbove100.person_id = tRvDateOfCollection.person_id
+left join(
+select person_id , rvDateOfArrival from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'rvDateOfArrival', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Date of Arrival Of Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Date of Arrival Of Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tRvDateOfArrival on tVlloadAbove100.person_id = tRvDateOfArrival.person_id
+left join(
+select person_id , adherencefailure , obs_datetime as 'adherencefailuredate' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_numeric as 'adherencefailure', voided from obs where concept_id =
+(select concept_id from concept_name where name = "Viral Load Value , Adherence Failure" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Viral Load Value , Adherence Failure" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tvlAdherenceFailure on tVlloadAbove100.person_id = tvlAdherenceFailure.person_id
+left join (
+select pid , tConceptname.name as 'outcomeAfterRepeat' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Outcome Action' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Repeat Viral,Outcome Action' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join (
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tOutcomeAfterRepeatVL on tVlloadAbove100.person_id = tOutcomeAfterRepeatVL.pid
+left join (
+select pid , tConceptname.name as 'mdtHeld' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'MDT Held?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'MDT Held?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join (
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tMdtHeld on tVlloadAbove100.person_id = tMdtHeld.pid
+left join(
+select person_id , mdtChangeDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'mdtChangeDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date MDT Held' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date MDT Held' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMdtChangeDate on tVlloadAbove100.person_id = tMdtChangeDate.person_id
+left join (
+select distinct(pid), regimenchangedto , date_activated from (
+select distinct(patient_id) as pid,row_num, date_activated , name as 'regimenchangedto' from(
+select @row_num :=IF(@prev_value=patient_id and @prev_drugId <> o.concept_id ,@row_num+1, 1) AS row_num,
+@prev_value:=patient_id, @prev_drugId:= o.concept_id, o.patient_id, o.concept_id , dr.name , o.encounter_id , o.voided , o.date_activated , o.date_created
+from orders o
+left join drug dr on o.concept_id = dr.concept_id
+where o.voided = 0 and dr.dosage_form = (select concept_id from concept_name where name = 'HIVTC, ART Regimen' and
+ concept_name_type = 'FULLY_SPECIFIED' and voided = 0 )
+and dr.name in ('1a = AZT/3TC+EFV' , '1b = AZT/3TC/NVP', '1c = TDF/3TC/DTG','1d=ABC/3TC (600/300)/DTG',
+'1e = AZT/3TC +DTG','1f = TDF/3TC+EFV','1g = TDF/3TC+NVP', '1h = TDF/FTC/EFV','2a=AZT/3TC+DTG' , '2b=ABC/3TC+DTG', '2c=TDF+3TC+LPV/r','2d=TDF/3TC+ATV/r',
+'2e=TDF/FTC-LPV/r','2f=TDF/FTC-ATV/r','2g=AZT/3TC+LPV/r', '2h=AZT/3TC+ATV/r','2i=ABC/3TC+LPV/r','2j=ABC/3TC+ATV/r','2k=TDF/3TC/DTG')
+order by patient_id, date_activated) b where row_num = 2
+)tSubRegimen
+)tRegimenSwitchedTo on tRegimenSwitchedTo.pid = tMdtChangeDate.person_id
+left join(
+select person_id , summary from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'summary', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Adherence Failure Summary' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Adherence Failure Summary' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+group by pid) c on a.person_id = c.pid and a.encounter_id = c.maxdate
+)tComments on tVlloadAbove100.person_id = tComments.person_id
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/hivExposedInfantRegisterForthTab.sql b/openmrs/apps/reports/sql/hivExposedInfantRegisterForthTab.sql
new file mode 100644
index 000000000..1bbfa1526
--- /dev/null
+++ b/openmrs/apps/reports/sql/hivExposedInfantRegisterForthTab.sql
@@ -0,0 +1,270 @@
+ select clientName as 'Infants Name', appointment_date_six as 'Visit Details -\nAppointment 6' , visit_date_six as 'Visit Details -\nVisit Date 6',TIMESTAMPDIFF(MONTH,birthdate, visit_date_six) as 'Visit Details -\nSixth Visit Age(Months)',Feeding_Code6 as 'Feeding Code -\nVisit 6',Immunization_Code6 as 'Immunization Code -\nVisit 6',ctx_visit6 as 'Visit 6 -\nCTX/ARV prophylaxis (Y/N)', appointment_date_seven as 'Visit Details -\nAppointment 7',
+ visit_date_seven as 'Visit Details -\nVisit Date 7',TIMESTAMPDIFF(MONTH,birthdate, visit_date_seven) as 'Seventh Details -\nFirst Visit Age(Months)',Feeding_Code7 as 'Feeding Code -\nVisit 7', Immunization_Code7 as 'Immunization Code -\nVisit 7' ,ctx_visit7 as 'Visit 7 -\nCTX/ARV prophylaxis (Y/N)',appointment_date_eight as 'Visit Details -\nAppointment 8', visit_date_eight as 'Visit Details -\nVisit Date 8',TIMESTAMPDIFF(MONTH,birthdate, visit_date_eight) as 'Visit Details -\nEighth Visit Age(Months)',Feeding_Code8 as 'Feeding Code -\nVisit 8',
+ Immunization_Code8 as 'Immunization Code -\nVisit 8',ctx_visit8 as 'Visit 8 -\nCTX/ARV prophylaxis (Y/N)', appointment_date_nine as 'Visit Details -\nAppointment 9', visit_date_nine as 'Visit Details -\nVisit Date 9',TIMESTAMPDIFF(MONTH,birthdate, visit_date_nine) as 'Visit Details -\nNineth Visit Age(Months)',Feeding_Code9 as 'Feeding Code -\nVisit 9',Immunization_Code9 as 'Immunization Code -\nVisit 9',ctx_visit9 as 'Visit 9 -\nCTX/ARV prophylaxis (Y/N)',
+ appointment_date_ten as 'Visit Details -\nAppointment 10', visit_date_ten as 'Visit Details -\nVisit Date 10' , TIMESTAMPDIFF(MONTH,birthdate, visit_date_ten) as 'Visit Details -\nTenth Visit Age(Months)',Feeding_Code10 as 'Feeding Code -\nVisit 10',Immunization_Code10 as 'Immunization Code -\nVisit 10',ctx_visit10 as 'Visit 10 -\nCTX/ARV prophylaxis (Y/N)' from (
+select person_id as pid , (SELECT @a:= 0) AS a ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEnrollementDate
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 2
+)HeiDemographics on tEnrollementDate.pid = HeiDemographics.person_id
+left join (
+select pid, appointment_date_six ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_six' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =6 order by pid
+)tAppointmentSix on tEnrollementDate.pid = tAppointmentSix.pid
+left join (
+select pid, appointment_date_seven ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_seven' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =7 order by pid
+)tAppointmentSeven on tEnrollementDate.pid = tAppointmentSeven.pid
+left join (
+select pid, appointment_date_eight ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_eight' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =8 order by pid
+)tAppointmentEight on tEnrollementDate.pid = tAppointmentEight.pid
+left join (
+select pid, appointment_date_nine ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_nine' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num = 9 order by pid
+)tAppointmentNine on tEnrollementDate.pid = tAppointmentNine.pid
+left join (
+select pid, appointment_date_ten ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_ten' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num = 10 order by pid
+)tAppointmentTen on tEnrollementDate.pid = tAppointmentTen.pid
+
+left join (
+select patient_id , date_started as visit_date_six, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 7
+)tVisitSix on tEnrollementDate.pid = tVisitSix.patient_id
+left join (
+select patient_id , date_started as visit_date_seven, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 8
+)tVisitSeven on tEnrollementDate.pid = tVisitSeven.patient_id
+left join (
+select patient_id , date_started as visit_date_eight, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 9
+)tVisitEight on tEnrollementDate.pid = tVisitEight.patient_id
+left join (
+select patient_id , date_started as visit_date_nine, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 10
+)tVisitNine on tEnrollementDate.pid = tVisitNine.patient_id
+left join (
+select patient_id , date_started as visit_date_ten, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 11
+)tVisitTen on tEnrollementDate.pid = tVisitTen.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code6' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 7
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitSixFeedingCode on tEnrollementDate.pid = tVisitSixFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code7' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 8
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitSevenFeedingCode on tEnrollementDate.pid = tVisitSevenFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code8' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 9
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitEightFeedingCode on tEnrollementDate.pid = tVisitEightFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code9' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 10
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitNineFeedingCode on tEnrollementDate.pid = tVisitNineFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code10' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 11
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitTenFeedingCode on tEnrollementDate.pid = tVisitTenFeedingCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code6' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 6
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tSixImmunizationCode on tEnrollementDate.pid = tSixImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code7' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 7
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tSevenImmunizationCode on tEnrollementDate.pid = tSevenImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code8' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 8
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tEightImmunizationCode on tEnrollementDate.pid = tEightImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code9' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 9
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tNineImmunizationCode on tEnrollementDate.pid = tNineImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code10' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 10
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tTenImmunizationCode on tEnrollementDate.pid = tTenImmunizationCode.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit6' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 7
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit6 on tEnrollementDate.pid = tctxVisit6.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit7' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 8
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit7 on tEnrollementDate.pid = tctxVisit7.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit8' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 9
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit8 on tEnrollementDate.pid = tctxVisit8.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit9' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 10
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit9 on tEnrollementDate.pid = tctxVisit9.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit10' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 11
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit10 on tEnrollementDate.pid = tctxVisit10.patient_id
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabFirst.sql b/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabFirst.sql
new file mode 100644
index 000000000..8d1b31140
--- /dev/null
+++ b/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabFirst.sql
@@ -0,0 +1,288 @@
+
+select @a:=@a+1 as 'Serial Number', enrollmentdateatart as 'Date of enrolment', HEI_Number as 'Exposed Infant Number' , ClientName as "Infant's Name", birthdate as 'Date of Birth' , Age , sex as 'Sex (M/F)',
+Clinic_Referred_from as 'Clinic Referred from', arvProphylaxisStartageMonths as 'Age at ARV prophylaxis Initiation (Months)', ctxStartAgeMonth as 'Age at Cotrimaxazole initiation (months)', firstpcrdate ,
+ mothersname as "Mother/Caregiver's Name" , telephonenumber as "Mother/Caregiver's : Telephone number", motherancnumber as "Mother’s ANC No" , artnumber as 'Mother ART Number' ,
+ artRegimenDuringPregnancy as "Mother’s ART for PMTCT - Antenatal ", artRegimenduringDelivery as "Mother’s ART for PMTCT - Delivery",
+arvMotherDishargedwith as "Mother’s ART for PMTCT - Post natal", infantriskstatus as "Infant's risk status (Low or High)" , (case when infantpmtctArvs = 'Daily NVP' then 1 when infantpmtctArvs = 'AZT+NVP' then 0 else 'N/A' end) as 'Infant’s ARVs for PMTCT: (1=NVP; 2=NVP+AZT; 3=None)',
+firstPcrTestDate as 'Initial Sample - Date', pcrRepeatTest as 'Repeat - Date' , datefirstpcrresultreceived as '1st DNA PCR Test:\nDate DBS was collected', ageFirstDBSMonths as "Age at 1st DBS (Weeks/Month)",firstfeedingmethodMethod as "1st DNA PCR Test:\nInfant Feeding Status" ,
+firstPcrResults as '1st DNA PCR Test:\nTest Result' , datefirstpcrresultreceived as '1st DNA PCR Test:\nDate result Received' , dateResultGivenToCaregiver as '1st DNA PCR Test:\nDate result given to caregiver'
+from (
+select person_id as pid , (SELECT @a:= 0) AS a ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEnrollementDate
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 2
+)HeiDemographics on tEnrollementDate.pid = HeiDemographics.person_id
+left join (
+select * from (
+select person_id, concept_id, value_datetime as 'firstpcrdate' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFirstPcrDate on tEnrollementDate.pid = tFirstPcrDate.person_id
+left join (
+select * from (
+select person_id, concept_id, value_datetime as 'datefirstpcrresultreceived' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'First PCR,Date results received' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'First PCR,Date results received' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDatefirstpcrresultreceived on tEnrollementDate.pid = tDatefirstpcrresultreceived.person_id
+left join (
+select pid , tConceptname.name as 'Clinic_Referred_from' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Entry Point(Enrollement)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Entry Point(Enrollement)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tEntryPoint on tEnrollementDate.pid = tEntryPoint.pid
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'arvProphylaxisStartageMonths',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV prophylaxis Initiation Age (Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV prophylaxis Initiation Age (Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvProphylaxisStartAge on tEnrollementDate.pid = tArvProphylaxisStartAge.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'ctxStartAgeMonth',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Cotrimoxazole initiation Age(Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Cotrimoxazole initiation Age(Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCtxStartAgeMonth on tEnrollementDate.pid = tCtxStartAgeMonth.person_id
+left join (
+select * from (
+select distinct(person_b) as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)tHeiToMotherRelationship
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'mothersname',
+ floor(datediff(curdate(),p.birthdate) / 365) as 'Mother_Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender = 'F' and gender is not null
+)tDemographics on tHeiToMotherRelationship.mother_id = tDemographics.person_id
+)tMothersDemographics on tEnrollementDate.pid = tMothersDemographics.hei_id
+left join (
+select pa.person_id , pa.value as 'telephonenumber'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'MobileNumber')
+)tMothersTel on tMothersDemographics.person_id = tMothersTel.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_text as 'motherancnumber',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMotherAnc on tMothersDemographics.mother_id = tMotherAnc.person_id
+left join(
+select pid , tConceptname.name as 'artRegimenDuringPregnancy' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Pregnacy' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Pregnacy' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tArtRegimenDuringPregnancy on tMothersDemographics.mother_id = tArtRegimenDuringPregnancy.pid
+left join(
+select pid , tConceptname.name as 'artRegimenduringDelivery' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Delivery' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tArtRegimenDuringDelivery on tMothersDemographics.mother_id = tArtRegimenDuringDelivery.pid
+left join (
+select pid , tConceptname.name as 'arvMotherDishargedwith' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Mother Discharged With' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ARV Mother Discharged With' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tarvMotherDishargedwith on tMothersDemographics.mother_id = tarvMotherDishargedwith.pid
+left join(
+select pid , tConceptname.name as 'infantriskstatus' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's Risk Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's Risk Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tInfantsRiskstatus on tEnrollementDate.pid = tInfantsRiskstatus.pid
+left join (
+select pid , tConceptname.name as 'infantpmtctArvs' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's PMTCT ARVS" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's PMTCT ARVS" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tInfantsPmtctArvs on tEnrollementDate.pid = tInfantsPmtctArvs.pid
+left join (
+select person_id as pid , firstPcrTestDate from (
+select person_id, concept_id, value_datetime as 'firstPcrTestDate' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFirstPCRTestDate on tEnrollementDate.pid = tFirstPCRTestDate.pid
+left join (
+select person_id as pid , pcrRepeatTest from (
+select person_id, concept_id, value_datetime as 'pcrRepeatTest' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Repeat PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Repeat PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tRepeatPCRDate on tEnrollementDate.pid = tRepeatPCRDate.pid
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'ageFirstDBSMonths',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Age at 1st DBS(Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Age at 1st DBS(Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAgeAtFirstDBSMoths on tEnrollementDate.pid = tAgeAtFirstDBSMoths.person_id
+left join(
+select pid , tConceptname.name as 'firstfeedingmethodMethod' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tInfantFeedingStatusFirstPCR on tEnrollementDate.pid = tInfantFeedingStatusFirstPCR.pid
+left join (
+select pid , tConceptname.name as 'firstPcrResults' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tFirstPcrResults on tEnrollementDate.pid = tFirstPcrResults.pid
+left join (
+select * from (
+select person_id, concept_id, value_datetime as 'dateResultGivenToCaregiver' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateResultsGivenToCareGiver on tEnrollementDate.pid = tDateResultsGivenToCareGiver.person_id
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabSecond.sql b/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabSecond.sql
new file mode 100644
index 000000000..e895fa5ec
--- /dev/null
+++ b/openmrs/apps/reports/sql/hivExposedInfantRegisterReportTabSecond.sql
@@ -0,0 +1,137 @@
+select clientName as 'Infants Name',
+DateofTest9Months as 'HIV Rapid Test (9 mo of age or first contact after) -\nDate of Test',
+(case when DateofTest9Months > birthdate then TIMESTAMPDIFF(MONTH, birthdate, DateofTest9Months) else 'N/A' end) as 'HIV Rapid Test (9 mo of age or first contact after) -\nAge (months)' ,
+(case when 9monthsResults = 'Negative' then 'Neg' when 9monthsResults = 'Positive' then 'Pos' else 'N/A' end ) as 'HIV Rapid Test (9 mo of age or first contact after) -\nRapid Test Result (Pos/Neg)',
+ DateofSecondPCR as '2nd DNA PCR Test -\nInitial' , DateofRepeatPCR as '2nd DNA PCR Test -\nRepeat', DateDBSCollected as '2nd DNA PCR Test -\nDate DBS was collected',
+ (case when ReasonForSecondPCR = 'For confirmation of positive first DNA PCR test result' then 1 when ReasonForSecondPCR = 'For Repeat DNA PCR 6 weeks after weaning for children less than 9 months' then 2 when ReasonForSecondPCR = 'For positive HIV rapid test result at 9 months or thereafter' then 3 else 'N/A' end) as '2nd DNA PCR Test-\nReason for 2nd PCR\n1.For confirmation of positive first DNA PCR test result\n2.For Repeat DNA PCR 6 weeks after weaning for children less than 9 months\n3.For positive HIV rapid test result at 9 months or thereafter\n(use codes below:1,2,3)',
+ ageSecondPCR as '2nd DNA PCR Test -\nAge at 2nd DBS (Months)' , InfantFeedingStatusSecondPCR as '2nd DNA PCR Test -\nInfant feeding status', SecondPCRresults as '2nd DNA PCR Test -\nTest Result', DateResultsReceivedSecondPCR as '2nd DNA PCR Test -\nDate result received',
+ DateResultGivenToCaregiver as '2nd DNA PCR Test -\nDate result given to caretaker' from(
+select person_id as pid , (SELECT @a:= 0) AS a ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEnrollementDate
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 2
+)HeiDemographics on tEnrollementDate.pid = HeiDemographics.person_id
+left join (
+select person_id , DateofTest9Months from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateofTest9Months', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateofTest9Months on tEnrollementDate.pid = tDateofTest9Months.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = 9monthsResults and concept_name_type = 'SHORT') as '9monthsResults' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as '9monthsResults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Rapid Test At 9 Months Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)t9MonthsResults on tEnrollementDate.pid = t9MonthsResults.person_id
+left join (
+select person_id , DateofSecondPCR from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateofSecondPCR', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateofSecondPCR on tEnrollementDate.pid = tDateofSecondPCR.person_id
+left join (
+select person_id , DateofRepeatPCR from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateofRepeatPCR', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Repeat PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Repeat PCR Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateofRepeatPCR on tEnrollementDate.pid = tDateofRepeatPCR.person_id
+left join (
+select person_id , DateDBSCollected from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateDBSCollected', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date sample receipt by PHL confirmed(Second PCR Test)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date sample receipt by PHL confirmed(Second PCR Test)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateDBSCollected on tEnrollementDate.pid = tDateDBSCollected.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = ReasonForSecondPCR and concept_name_type = 'SHORT') as 'ReasonForSecondPCR' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'ReasonForSecondPCR', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Reason For Second PCR' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Reason For Second PCR' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tReasonForSecondPCR on tEnrollementDate.pid = tReasonForSecondPCR.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime , value_numeric as 'ageSecondPCR',encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Second PCR,Age at 2nd DBS (Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Second PCR,Age at 2nd DBS (Months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAgeSecondPCR on tEnrollementDate.pid = tAgeSecondPCR.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = InfantFeedingStatusSecondPCR and concept_name_type = 'SHORT') as 'InfantFeedingStatusSecondPCR' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'InfantFeedingStatusSecondPCR', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Feeding Method)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tInfantFeedingStatusSecondPCR on tEnrollementDate.pid = tInfantFeedingStatusSecondPCR.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = SecondPCRresults and concept_name_type = 'SHORT') as 'SecondPCRresults' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'SecondPCRresults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSecondPCRresults on tEnrollementDate.pid = tSecondPCRresults.person_id
+left join (
+select person_id , DateResultsReceivedSecondPCR from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateResultsReceivedSecondPCR', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Second PCR,Date result Received' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Second PCR,Date result Received' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateResultsReceivedSecondPCR on tEnrollementDate.pid = tDateResultsReceivedSecondPCR.person_id
+left join (
+select person_id , DateResultGivenToCaregiver from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateResultGivenToCaregiver', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (Second PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateResultGivenToCaregiver on tEnrollementDate.pid = tDateResultGivenToCaregiver.person_id
diff --git a/openmrs/apps/reports/sql/hivExposedInfantRegisterTabFive.sql b/openmrs/apps/reports/sql/hivExposedInfantRegisterTabFive.sql
new file mode 100644
index 000000000..c47642bea
--- /dev/null
+++ b/openmrs/apps/reports/sql/hivExposedInfantRegisterTabFive.sql
@@ -0,0 +1,64 @@
+select clientName as 'Infants Name', DateTested18Months as 'Confirmatory HIV Rapid Test (at 18 months or later) -\nDate Tested',
+ (case when DateTested18Months > birthdate then TIMESTAMPDIFF(MONTH, birthdate, DateTested18Months) else 'N/A' end) as 'Confirmatory HIV Rapid Test (at 18 months or later) -\nAge(Months)',
+ (case when RapidResults18Months = 'Negative' then 'Neg' when RapidResults18Months = 'Positive' then 'Pos' else 'N/A' end ) as 'Confirmatory HIV Rapid Test (at 18 months or later) -\nRapid Test Result (Pos=Positive, Neg=Negative)', FinalOutcome as 'Final Outcome',
+ (case when FinalOutcome = 'Transferred' then FacilityTransferredTo else 'N/A' end) as 'Facility Name Transferred To' from (
+select person_id as pid , (SELECT @a:= 0) AS a ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEnrollementDate
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 2
+)HeiDemographics on tEnrollementDate.pid = HeiDemographics.person_id
+left join (
+select person_id , DateTested18Months from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'DateTested18Months', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Date)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateTested18Months on tEnrollementDate.pid = tDateTested18Months.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = RapidResults18Months and concept_name_type = 'SHORT') as 'RapidResults18Months' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'RapidResults18Months', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (18Months Rapid Test Results)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)t18RapidResults on tEnrollementDate.pid = t18RapidResults.person_id
+left join (
+select person_id, (select name from concept_name where concept_id = FinalOutcome and concept_name_type = 'SHORT') as 'FinalOutcome' from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'FinalOutcome', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Final Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Final Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFinalOutcome on tEnrollementDate.pid = tFinalOutcome.person_id
+left join (
+select person_id , FacilityTransferredTo from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'FacilityTransferredTo', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Facility Transferred to' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Facility Transferred to' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tFacilityTransferredTo on tEnrollementDate.pid = tFacilityTransferredTo.person_id
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/hivExposedInfantRegisterTabThird.sql b/openmrs/apps/reports/sql/hivExposedInfantRegisterTabThird.sql
new file mode 100644
index 000000000..82f7dfc88
--- /dev/null
+++ b/openmrs/apps/reports/sql/hivExposedInfantRegisterTabThird.sql
@@ -0,0 +1,279 @@
+select clientName as 'Infants Name',
+appointment_date_one as 'Visit Details -\nAppointment 1' ,visit_date_one as 'Visit Details -\nVisit Date 1',TIMESTAMPDIFF(MONTH,birthdate, visit_date_one) as 'Visit Details -\nFirst Visit Age(Months)',Feeding_Code1 as 'Feeding Code -\nVisit 1',Immunization_Code1 as 'Immunization Code -\nVisit 1',ctx_visit1 as 'Visit 1 -\nCTX/ARV prophylaxis (Y/N)',appointment_date_two as 'Visit Details -\nAppointment 2',
+ visit_date_two as 'Visit Details -\nVisit Date 2', TIMESTAMPDIFF(MONTH,birthdate, visit_date_two) as 'Visit Details -\nSecond Visit Age(Months)', Feeding_Code2 as 'Feeding Code -\nVisit 2',Immunization_Code2 as 'Immunization Code -\nVisit 2',ctx_visit2 as 'Visit 2 -\nCTX/ARV prophylaxis (Y/N)',appointment_date_three as 'Visit Details -\nAppointment 3', visit_date_three as 'Visit Details -\nVisit Date 3',
+ TIMESTAMPDIFF(MONTH,birthdate, visit_date_three) as 'Visit Details -\nThird Visit Age(Months)',Feeding_Code3 as 'Feeding Code -\nVisit 3',Immunization_Code3 as 'Immunization Code -\nVisit 3',ctx_visit3 as 'Visit 3 -\nCTX/ARV prophylaxis (Y/N)',
+ appointment_date_four as 'Visit Details -\nAppointment 4' ,visit_date_four as 'Visit Details -\nVisit Date 4',TIMESTAMPDIFF(MONTH,birthdate, visit_date_four) as 'Visit Details -\nFourth Visit Age(Months)', Feeding_Code4 as 'Feeding Code -\nVisit 4',Immunization_Code4 as 'Immunization Code -\nVisit 4',ctx_visit4 as 'Visit 4 -\nCTX/ARV prophylaxis (Y/N)',
+ appointment_date_five as 'Visit Details -\nAppointment 5', visit_date_five as 'Visit Details -\nVisit Date 5',TIMESTAMPDIFF(MONTH,birthdate, visit_date_five) as 'Visit Details -\nFifth Visit Age(Months)', Feeding_Code5 as 'Feeding Code -\nVisit 5', Immunization_Code5 as 'Immunization Code -\nVisit 5', ctx_visit5 as 'Visit 5 -\nCTX/ARV prophylaxis (Y/N)'
+ from (
+select person_id as pid , (SELECT @a:= 0) AS a ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEnrollementDate
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 2
+)HeiDemographics on tEnrollementDate.pid = HeiDemographics.person_id
+left join (
+select pid, appointment_date_one ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_one' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =1 order by pid
+)tAppointmentOne on tEnrollementDate.pid = tAppointmentOne.pid
+left join (
+select pid, appointment_date_two ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_two' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =2 order by pid
+)tAppointmentTwo on tEnrollementDate.pid = tAppointmentTwo.pid
+left join (
+select pid, appointment_date_three ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_three' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =3 order by pid
+)tAppointmentThree on tEnrollementDate.pid = tAppointmentThree.pid
+left join (
+select pid, appointment_date_four ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_four' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =4 order by pid
+)tAppointmentFour on tEnrollementDate.pid = tAppointmentFour.pid
+left join (
+select pid, appointment_date_five ,row_num from (
+select pa.person_id as pid, @row_num :=IF(@prev_value=pa.person_id,@row_num+1, 1) AS row_num, @prev_value:=pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , pt_app.start_date_time as 'appointment_date_five' , pt_app.voided
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+LEFT JOIN patient_appointment as pt_app on pt.patient_id = pt_app.patient_id
+where pa.person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient') and
+pa.value in (select concept_id from concept_name where name in ('HeiRelationship',"ExistingHeiRelationship") and concept_name_type = 'FULLY_SPECIFIED') and pt_app.voided = 0 and pt_app.status != 'Cancelled'
+and (datediff(curdate(),p.birthdate) / 365) < 2
+)tAppointmentOne where row_num =5 order by pid
+)tAppointmentFive on tEnrollementDate.pid = tAppointmentFive.pid
+
+left join (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 2
+)tVisitOne on tEnrollementDate.pid = tVisitOne.patient_id
+left join (
+select patient_id , date_started as visit_date_two, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 3
+)tVisitTwo on tEnrollementDate.pid = tVisitTwo.patient_id
+left join (
+select patient_id , date_started as visit_date_three, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 4
+)tVisitThree on tEnrollementDate.pid = tVisitThree.patient_id
+left join (
+select patient_id , date_started as visit_date_four, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 5
+)tVisitFour on tEnrollementDate.pid = tVisitFour.patient_id
+left join (
+select patient_id , date_started as visit_date_five, date_stopped from (
+select patient_id ,@row_num := IF(@prev_value = patient_id,@row_num+1,1) AS row_num,@prev_value:= patient_id, date_started, date_stopped ,
+visit_id, voided from visit
+order by patient_id
+)tVisitOne where row_num = 6
+)tVisitFive on tEnrollementDate.pid = tVisitFive.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code1' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 2
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitOneFeedingCode on tEnrollementDate.pid = tVisitOneFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code2' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 3
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitTwoFeedingCode on tEnrollementDate.pid = tVisitTwoFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code3' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 4
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitThreeFeedingCode on tEnrollementDate.pid = tVisitThreeFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code4' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 5
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitFourFeedingCode on tEnrollementDate.pid = tVisitFourFeedingCode.patient_id
+left join (
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Feeding_Code5' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 6
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Infant Feeding' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tVisitFiveFeedingCode on tEnrollementDate.pid = tVisitFiveFeedingCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code1' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 2
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tFirstImmunizationCode on tEnrollementDate.pid = tFirstImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code2' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 3
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tSecondImmunizationCode on tEnrollementDate.pid = tSecondImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code3' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 4
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tThirdImmunizationCode on tEnrollementDate.pid = tThirdImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code4' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 5
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tFourthImmunizationCode on tEnrollementDate.pid = tFourthImmunizationCode.patient_id
+left join(
+select patient_id, (select name from concept_name where concept_id = value_coded and concept_name_type = 'SHORT') as 'Immunization_Code5' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 6
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Immunization Code' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tFifthImmunizationCode on tEnrollementDate.pid = tFifthImmunizationCode.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit1' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 2
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit1 on tEnrollementDate.pid = tctxVisit1.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit2' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 3
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit2 on tEnrollementDate.pid = tctxVisit2.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit3' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 4
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit3 on tEnrollementDate.pid = tctxVisit3.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit4' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 5
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit4 on tEnrollementDate.pid = tctxVisit4.patient_id
+left join(
+select patient_id, (case when value_coded = 1 then 'Y' else 'N' end) as 'ctx_visit5' from (
+select patient_id , date_started as visit_date_one, date_stopped from (
+select v.patient_id ,@row_num := IF(@prev_value = v.patient_id,@row_num+1,1) AS row_num,@prev_value:= v.patient_id, v.date_started, v.date_stopped ,
+v.visit_id, v.voided from visit v order by v.patient_id )tVisitOne where row_num = 6
+)firstvisit inner join (select person_id as pid, obs_datetime , voided ,value_coded from obs where concept_id = (select concept_id from concept_name where name = 'Cotrimoxazole/Dapsone' and
+concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0) c
+on firstvisit.patient_id = c.pid and DATE_FORMAT(c.obs_datetime, "%Y-%m-%d") = DATE_FORMAT(firstvisit.visit_date_one, "%Y-%m-%d")
+)tctxVisit5 on tEnrollementDate.pid = tctxVisit5.patient_id
+
+
+
+
+
+
diff --git a/openmrs/apps/reports/sql/indextesting_masterindex.sql b/openmrs/apps/reports/sql/indextesting_masterindex.sql
new file mode 100644
index 000000000..57d221ab4
--- /dev/null
+++ b/openmrs/apps/reports/sql/indextesting_masterindex.sql
@@ -0,0 +1,98 @@
+select ClientName as 'Index Name' , artnumber as 'ART Number' , Names as 'Contact Name' ,PhoneNumber as 'Contact Phone Number' , wasContacted as 'Contacted ?' , wasContactTested as 'Tested ?' from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+sexual_partner as 'Sexual Partner',
+(case when sexual_partner = 'YES' then sexual_partner_phone_number else family_member_phonenumber end) as 'PhoneNumber',
+(case when sexual_partner = 'YES' then sexualPartnerContacted else familyMemberContacted end) as 'wasContacted',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_phonenumber'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member,Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberMobile on tSexualRelationship.obs_group_id = tFamilyMemberMobile.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_phone_number'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner, Phone Number' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerPhoneNumber on tSexualRelationship.obs_group_id = tSexualPartnerPhoneNumber.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerContacted on tSexualRelationship.obs_group_id = tSexualPartnerContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberContacted'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Contacted?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberContacted on tSexualRelationship.obs_group_id = tFamilyMemberContacted.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+
+
+
+
diff --git a/openmrs/apps/reports/sql/maternitypmtct.sql b/openmrs/apps/reports/sql/maternitypmtct.sql
new file mode 100644
index 000000000..79a94ab3f
--- /dev/null
+++ b/openmrs/apps/reports/sql/maternitypmtct.sql
@@ -0,0 +1,268 @@
+select @a:=@a+1 as 'Serial Number' , dateMotherVisitedMaternity as 'Date of visit' , ClientName as 'Mothers Name' , IFNULL(telephonenumber,'N/A') as 'Telephone number', Age , ifnull(address5,'N/A') as 'Name of village or Address' , ancnummber
+as 'ANC Number' , maternitynumber as 'Maternity Number' , artnumber as 'ART No' , results as 'Previous HIV test result (recent/ within 6 months)\nTest Result' ,
+placetestedhiv as 'Previous HIV test result (recent/ within 6 months)\nPlace Tested' , datetestedhiv as 'Previous HIV test result (recent/ within 6 months)\nDate Tested' ,
+(case when ismothertestedinmaternity = 1 then datetestedinmaternity else 'N/A' end) as 'Date tested in Maternity' , finalresultaftertestinginmaternity as 'Final Result After testing \nin maternity',
+(case when finalresultaftertestinginmaternity = 'Positive' then artRegimenDuringPregnancyResults else 'N/A' end) as 'ART Regimen During Pregnancy',
+(case when finalresultaftertestinginmaternity = 'Positive' then durationinartResults else 'N/A' end) as 'Duration on ART' ,
+ infantriskstatusResults as "Infant's Risk Status" ,
+(case when finalresultaftertestinginmaternity = 'Positive' then concat("1 : ", " ", artRegimenDuringPregnancyResults) when finalresultaftertestinginmaternity = 'Negative' then 0 else 'N/A' end) as 'ART: Newly Started in Labour:\n(0=No 1= yes 2=N/A):\nIf yes, indicate the regimen in the lower cell' ,
+(case when infantpmtctarvsresults = 'Daily NVP' then 1 when infantpmtctarvsresults = 'AZT+NVP' then 2 else 'N/A' end) as 'Infant ARV Prophylaxis 1=NVP , 2=AZT+NVP:\nARV Code',
+(case when infantpmtctarvsresults = 'Daily NVP' then nvpDate when infantpmtctarvsresults = 'AZT+NVP' then aztnvpDate else 'N/A' end) as 'Infant ARV Prophylaxis 1=NVP , 2=AZT+NVP:\nDate Given',
+(case when infantpmtctarvsresults = 'Daily NVP' then 1 when infantpmtctarvsresults = 'AZT+NVP' then 2 else 'N/A' end) as 'ARV Baby Discharged with :\n1=NVP , 2=AZT+NVP',
+(case when infantdeedingResults = 'EBF' then 1 when infantdeedingResults = 'RF' then 2 when infantdeedingResults = 'Mixed Feeding(> 6 Months)' then 3 else 'N/A' end) as 'Infant Feeding practice:\n 1=EBF 2=RF 3=MF',
+heinumber as 'Exposed Infant Number'
+from (
+select (SELECT @a:= 0) AS a ,person_id as pid, dateMotherVisitedMaternity
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'dateMotherVisitedMaternity', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMaternityVisitDate left join
+(
+select person_b as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)texposedInfantNumber on tMaternityVisitDate.pid = texposedInfantNumber.mother_id
+left join
+(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender = 'F' and gender is not null
+)tDemogrpahics on tMaternityVisitDate.pid = tDemogrpahics.person_id
+left join (
+select person_id, ancnummber from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'ancnummber', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_text is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAncNumber on tMaternityVisitDate.pid = tAncNumber.person_id
+left join(
+select person_id, maternitynumber from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'maternitynumber', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_text is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'ANC No' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tMaternityNumber on tMaternityVisitDate.pid = tMaternityNumber.person_id
+left join (
+select person_id , results from (
+select person_id, testResultWithin6months from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'testResultWithin6months', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Previous HIV test result(Within 6 months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Previous HIV test result(Within 6 months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'results' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.testResultWithin6months = tConceptname.concept_id
+)tResultswithin6Months on tMaternityVisitDate.pid = tResultswithin6Months.person_id
+left join (
+select person_id, placetestedhiv from (
+select person_id, concept_id, obs_datetime , encounter_id , value_text as 'placetestedhiv', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Place Test Hiv' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_text is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Place Test Hiv' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tplaceTestedHiv on tMaternityVisitDate.pid = tplaceTestedHiv.person_id
+left join (
+select person_id , datetestedhiv from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'datetestedhiv', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date Test Hiv' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date Test Hiv' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateTestedHiv on tMaternityVisitDate.pid = tDateTestedHiv.person_id
+left join (
+select person_id , ismothertestedinmaternity from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'ismothertestedinmaternity', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Mother tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Mother tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsmothertestedinmaternity on tMaternityVisitDate.pid = tIsmothertestedinmaternity.person_id
+left join (
+select person_id , datetestedinmaternity from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'datetestedinmaternity', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Date tested in Maternity' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateTestedinMaternity on tMaternityVisitDate.pid = tDateTestedinMaternity.person_id
+left join (
+select person_id , finalresultaftertestinginmaternity from (
+select person_id, finalmaternityresults from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'finalmaternityresults', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Status After Testing HIV' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, Status After Testing HIV' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'finalresultaftertestinginmaternity' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.finalmaternityresults = tConceptname.concept_id
+)tFinalResultAfterTestingInmaternity on tMaternityVisitDate.pid = tFinalResultAfterTestingInmaternity.person_id
+left join(
+select person_id , artRegimenDuringPregnancyResults from (
+select person_id, artregimenduringpregnancy from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'artregimenduringpregnancy', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Pregnacy' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card, ART Regimen During Pregnacy' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'artRegimenDuringPregnancyResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.artregimenduringpregnancy = tConceptname.concept_id
+)tArtRegimenDuringPRegnancy on tMaternityVisitDate.pid = tArtRegimenDuringPRegnancy.person_id
+left join (
+select person_id , durationinartResults from (
+select person_id, durationinart from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'durationinart', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Duration on ART?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Duration on ART?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'durationinartResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.durationinart = tConceptname.concept_id
+)tDurationOnArts on texposedInfantNumber.hei_id = tDurationOnArts.person_id
+left join (
+select person_id , infantriskstatusResults from (
+select person_id, infantriskstatus from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'infantriskstatus', voided from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's Risk Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's Risk Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'infantriskstatusResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.infantriskstatus = tConceptname.concept_id
+)tInfantsRiskStatus on tMaternityVisitDate.pid = tInfantsRiskStatus.person_id
+left join (
+select person_id , ARTNewlystartedinLabor from (
+select person_id, artNewlyStarted from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'artNewlyStarted', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card,ART Newly Started in Labor' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Maternity card,ART Newly Started in Labor' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'ARTNewlystartedinLabor' from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tresults.artNewlyStarted = tConceptname.concept_id
+)tArtStartedInLabour on tMaternityVisitDate.pid = tArtStartedInLabour.person_id
+left join (
+select person_id , infantpmtctarvsresults from (
+select person_id, infantpmtctarvs from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'infantpmtctarvs', voided from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's PMTCT ARVS" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Infant's PMTCT ARVS" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'infantpmtctarvsresults' from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tresults.infantpmtctarvs = tConceptname.concept_id
+)tInfantPmtctARV on texposedInfantNumber.hei_id = tInfantPmtctARV.person_id
+left join (
+select person_id , nvpDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'nvpDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Daily NVP Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Daily NVP Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tNvpDate on texposedInfantNumber.hei_id = tNvpDate.person_id
+left join (
+select person_id , aztnvpDate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'aztnvpDate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'AZT+NVP Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'AZT+NVP Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAztnvpDate on texposedInfantNumber.hei_id = tAztnvpDate.person_id
+left join (
+select person_id , infantdeedingResults from (
+select person_id, infantdeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'infantdeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Feeding' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded is not null and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Infant Feeding' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and
+obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tresults left join
+(
+select concept_id , name as 'infantdeedingResults' from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tresults.infantdeeding = tConceptname.concept_id
+)tInfantFeeding on texposedInfantNumber.hei_id = tInfantFeeding.person_id
+left join (
+select mother_id, eid , heinumber from (
+select person_b as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)heiRelationship
+left join(
+select pa.person_id as 'eid', pa.value as 'heinumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No') and gender is not null
+)tHeiDemographics on heiRelationship.hei_id = tHeiDemographics.eid
+)tHeiNumber on tMaternityVisitDate.pid = tHeiNumber.mother_id
+left join (
+select pa.person_id , pa.value as 'telephonenumber'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'MobileNumber')
+)tTelephonenumber on tMaternityVisitDate.pid = tTelephonenumber.person_id
+left join(
+select person_id , address5 , voided from person_address where voided = 0 and address5 is not null
+)tVillage on tMaternityVisitDate.pid = tVillage.person_id
+
diff --git a/openmrs/apps/reports/sql/missedAppointments.sql b/openmrs/apps/reports/sql/missedAppointments.sql
new file mode 100644
index 000000000..91bd8d15f
--- /dev/null
+++ b/openmrs/apps/reports/sql/missedAppointments.sql
@@ -0,0 +1,28 @@
+SELECT DISTINCT
+ pai.identifier AS 'Patient ID',
+ pn.given_name AS 'First Name',
+ ifnull(pn.family_name,'') AS 'Last Name',
+ pMobile.telephoneNo AS 'Telephone No.',
+ p.gender AS 'Gender',
+ DATE_FORMAT(obsConcept.artStartDate, "%d/%m/%Y") AS 'ART Start Date',
+ DATE_FORMAT(start_date_time, "%d/%m/%Y") AS 'Appointment Date'
+FROM patient_appointment pa
+ LEFT JOIN person p ON p.person_id = pa.patient_id AND pa.voided IS FALSE
+ LEFT JOIN person_name pn ON p.person_id = pn.person_id AND pn.voided IS FALSE
+ LEFT JOIN patient_identifier pai ON (pai.patient_id = pa.patient_id AND pai.preferred = 1)
+ LEFT JOIN (select paMobile.person_id as 'pMobilePersonId', paMobile.value AS 'telephoneNo' from person_attribute paMobile
+ JOIN person_attribute_type patMobile ON patMobile.name = "MobileNumber" AND patMobile.retired IS FALSE
+ AND patMobile.person_attribute_type_id = paMobile.person_attribute_type_id) AS pMobile ON pa.patient_id = pMobile.pMobilePersonId
+ LEFT JOIN (select pa_sup.person_id as 'pa_supPersonId', pa_sup.value AS 'paSupporterName' from person_attribute pa_sup
+ JOIN person_attribute_type patSup ON patSup.name = "TreatmentSupporterName" AND patSup.retired IS FALSE
+ AND patSup.person_attribute_type_id = pa_sup.person_attribute_type_id) AS pSupporter ON pa.patient_id = pSupporter.pa_supPersonId
+ LEFT JOIN (select paSupPhone.person_id as 'paSupPhonePersonId', paSupPhone.value AS 'paSupPhoneNumber' from person_attribute paSupPhone
+ JOIN person_attribute_type patSupPhone ON patSupPhone.name = "TreatmentSupporterTelephoneNumber" AND patSupPhone.retired IS FALSE
+ AND patSupPhone.person_attribute_type_id = paSupPhone.person_attribute_type_id) AS pSupPhone ON pa.patient_id = pSupPhone.paSupPhonePersonId
+ LEFT JOIN (SELECT o.value_datetime AS 'artStartDate', v.patient_id AS 'visitPatientId', v.visit_id AS visitId FROM visit v
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="ANC, ART Start Date")
+ JOIN encounter enc ON enc.visit_id = v.visit_id
+ JOIN obs o ON (o.encounter_id = enc.encounter_id and o.concept_id = cn.concept_id AND o.person_id = v.patient_id)
+ HAVING v.visit_id = (SELECT MAX(maxV.visit_id) as maxVisitId
+ FROM visit maxV WHERE maxV.patient_id = v.patient_id)) AS obsConcept ON obsConcept.visitPatientId = pa.patient_id
+WHERE pa.status = 'Missed' and pa.start_date_time BETWEEN '#startDate#' AND '#endDate#' ORDER BY pa.start_date_time DESC;
diff --git a/openmrs/apps/reports/sql/pmtctAncvisitandHivcouselling.sql b/openmrs/apps/reports/sql/pmtctAncvisitandHivcouselling.sql
new file mode 100644
index 000000000..d57bc9a3f
--- /dev/null
+++ b/openmrs/apps/reports/sql/pmtctAncvisitandHivcouselling.sql
@@ -0,0 +1,797 @@
+-- ANC Visits, Syphilis and HBV Testing
+
+SELECT
+ 'Total ANC Visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitNumberResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitNumberResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F'and visitNumberResult is not null) THEN 1 END overFifty,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'visitNumberResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Visit Number" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'First ANC visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'First ANC Mothers tested for Syphilis' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult in ("Positive","Negative")) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'First ANC Mothers testing Syphilis positive' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and rprvdrlResult = "Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Mothers tested for Syphilis (None First ANC visit mothers)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult in ("Positive","Negative")) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Mothers testing Syphilis positive (None First ANC visit mothers)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult not in ("1 = Second Contact") and rprvdrlResult = "Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Attending ANC four visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "4 = Fourth Contact") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Attending ANC more than four visits' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult in ("5 = Fifth Contact","6 = Sixth Contact","7 = Seventh Contact","8 = Eight Contact","9 = Eight Contact")) THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Mothers tested for HBV ' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitNumberResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitNumberResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitNumberResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitNumberResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitNumberResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F'and visitNumberResult is not null) THEN 1 END overFifty,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitNumberResult is not null) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_text AS 'visitNumberResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Hepatitis - B Sample" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Mothers tested HBV Positive' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END overFifty,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and hepBResult is not null and visitNumberResult is not null and rprvdrlResult = "Positive") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_text AS 'hepBResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Hepatitis - B Sample" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', o.value_coded AS 'visitNumberResult' FROM obs o
+ JOIN concept_name cn ON (cn.concept_name_type = "FULLY_SPECIFIED" AND cn.voided is false AND cn.name="Visit Number" and o.concept_id = cn.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr1 ON (vr1.visitPatientId = pn.person_id)
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'rprvdrlResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="RPR/VDRL" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+) p
+
+UNION ALL
+
+SELECT
+ 'Known positive status (at entry into) - ANC' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint = "ANC Clinic") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Known positive status at entry into ANC on ART' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint = "ANC Clinic" and artResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'artResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Transferred in on ART?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status tested for HIV (1st ANC Visit)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult is not null) THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Women of unknown status testing HIV positive (1st ANC visit)' as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total of HIV Positive women \n attending ANC (a+b)'as 'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypointhiv = "ANC Clinic" and visitResult = "1 = Second Contact" and hivSampleResult ="Positive") THEN 1 END totalAll
+
+ FROM person pn
+ LEFT JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypointhiv' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS hr ON (hr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'visitResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Visit Number" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId',(select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'hivSampleResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV Sample" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr1 ON (pr1.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'HIV infected pregnant women newly started on ART (Option B+)'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint not in ("ANC Clinic") and artResult = "True" and arvsResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'artResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Transferred in on ART?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'arvsResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Were ARVS Received?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS ar ON (ar.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Total of HIV Positive \n Pregnant women enrolled in PMTCT'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" and pmtcrResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pregResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="FP Pregnant" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pmtcrResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="PMTCT - HIV & ART Follow up" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS ar ON (ar.visitPatientId = pn.person_id)
+ ) p
+
+UNION ALL
+
+SELECT
+ 'Known positive status on ART Breastfeeding 'as'Title',
+ count(unkownage) as 'Unknown age',
+ count(tenTofourteen) as '10-14 YRS',
+ count(fifteenTonineteen) as '15-19 YRS',
+ count(twentyTotwentyfour) as '20-24 YRS',
+ count(twentyfiveTotwentynine) as '25-29 YRS',
+ count(thirtyTothirtyfour) as '30-34 YRS',
+ count(thirtyfiveTothirtynine) as '35-39 YRS',
+ count(fourtyToFourtyfour) as '40-44 YRS',
+ count(fourtyfiveToFourtynine) as '45-49 YRS',
+ count(overFifty) as '50+ YRS',
+ count(totalAll) as 'Total'
+
+ FROM (
+ SELECT
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 0 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END unkownage,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 10 and 14 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END tenTofourteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 15 and 19 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END fifteenTonineteen,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 20 and 24 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END twentyTotwentyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 25 and 29 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END twentyfiveTotwentynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 30 and 34 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END thirtyTothirtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 35 and 39 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END thirtyfiveTothirtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 40 and 44 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END fourtyToFourtyfour,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 45 and 49 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END fourtyfiveToFourtynine,
+ CASE WHEN (TIMESTAMPDIFF(YEAR, birthdate, CURDATE()) between 50 and 100 and gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True" ) THEN 1 END overFifty,
+ CASE WHEN (gender = 'F' and entrypoint not in ("ANC Clinic") and pregResult = "True") THEN 1 END totalAll
+
+ FROM person pn
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'entrypoint' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="HIV - Entry Point" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS pr ON (pr.visitPatientId = pn.person_id)
+ JOIN (SELECT distinct v.patient_id AS 'visitPatientId', (select name from concept_name where concept_id = o.value_coded and concept_name_type = "FULLY_SPECIFIED") AS 'pregResult' FROM obs o
+ JOIN concept_name cnr ON (cnr.concept_name_type = "FULLY_SPECIFIED" AND cnr.voided is false AND cnr.name="Currently Breastfeeding?" and o.concept_id = cnr.concept_id)
+ JOIN encounter enc ON enc.encounter_id = o.encounter_id
+ JOIN visit v ON v.visit_id = enc.visit_id
+ GROUP BY v.patient_id
+ ORDER BY v.visit_id DESC) AS vr ON (vr.visitPatientId = pn.person_id)
+ ) p
diff --git a/openmrs/apps/reports/sql/pmtct_fo_quarterly_report.sql b/openmrs/apps/reports/sql/pmtct_fo_quarterly_report.sql
new file mode 100644
index 000000000..d2563fd6f
--- /dev/null
+++ b/openmrs/apps/reports/sql/pmtct_fo_quarterly_report.sql
@@ -0,0 +1,64 @@
+select @a:=@a+1 as 'Serial' , date_of_birth as 'Date Of Birth', artnumber as 'EID Number' , Sex , date_eid_sample_collected as 'Date EID sample collected' ,zerototwomonths as 'Age of child at first EID sample collection\n(put 1 where the age belongs):\n0 - 2 months of age' ,
+abovetwomonths as 'Age of child at first EID sample collection\n(put 1 where the age belongs):\n2 - 12 months of age' ,
+(case when Outcomeat24months = 'HIV Infected' then 1 when Outcomeat24months = 'HIV uninfected' then 2 when Outcomeat24months = 'HIV Final Status Unknown' then 3 when Outcomeat24months = 'Died without status known' then 4 else 'N/A' end )
+as 'Final outcome at 24 months of age \n(1. HIV infected; 2- HIV-uninfected; 3-HIV final status unknown;4-Died without status known:' from (
+
+select (SELECT @a:= 0) AS a , pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,p.birthdate as 'date_of_birth' ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and (datediff(curdate(),p.birthdate) / 365) < 2 and p.birthdate between DATE_SUB(DATE_FORMAT('#startDate#','%Y-%m-01'), INTERVAL 2 YEAR)
+ and DATE_SUB(DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59'),INTERVAL 2 YEAR)
+)tDemogrpahics
+left join
+(
+select * from (
+select person_id, concept_id, value_datetime as 'date_eid_sample_collected' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date EID sample collected' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date EID sample collected' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateheisamplecollected on tDemogrpahics.person_id = tDateheisamplecollected.person_id
+left join
+(
+select tHeiage.person_id,
+case when (12 * (YEAR(date_of_first_eid) - YEAR(birthdate)) + (MONTH(date_of_first_eid) - MONTH(birthdate))) <= 2 then '1' else '' end as 'zerototwomonths',
+case when (12 * (YEAR(date_of_first_eid) - YEAR(birthdate)) + (MONTH(date_of_first_eid) - MONTH(birthdate))) > 2 and
+ (12 * (YEAR(date_of_first_eid) - YEAR(birthdate)) + (MONTH(date_of_first_eid) - MONTH(birthdate))) <= 12 then '1' else '' end as 'abovetwomonths'
+from(
+select * from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'date_of_first_eid', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date EID sample collected' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date EID sample collected' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHeiage left join
+(select person_id , birthdate from person
+)tbirthdate on tHeiage.person_id = tbirthdate.person_id
+)tHeiAgeatEidCollection on tDemogrpahics.person_id = tHeiAgeatEidCollection.person_id
+left join
+(
+select pid , tConceptname.name as 'Outcomeat24months' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Final outcome at 24 months of age' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Final outcome at 24 months of age' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'SHORT' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tOutcomeafter24months on tDemogrpahics.person_id = tOutcomeafter24months.pid
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/quartely_tx_ml.sql b/openmrs/apps/reports/sql/quartely_tx_ml.sql
new file mode 100644
index 000000000..5944d82a8
--- /dev/null
+++ b/openmrs/apps/reports/sql/quartely_tx_ml.sql
@@ -0,0 +1,1631 @@
+select 'less than a year' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age < 1 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age < 1 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age < 1 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age < 1 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age < 1 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age < 1 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age < 1 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age < 1 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age < 1 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age < 1 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '1 to 4 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 1 and age < 5 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 1 and age < 5 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 1 and age < 5 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 1 and age < 5 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 1 and age < 5 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 1 and age < 5 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 1 and age < 5 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 1 and age < 5 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 1 and age < 5 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 1 and age < 5 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '5 to 9 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 5 and age < 10 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 5 and age < 10 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 5 and age < 10 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 5 and age < 10 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 5 and age < 10 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 5 and age < 10 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 5 and age < 10 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 5 and age < 10 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 5 and age < 10 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 5 and age < 10 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '10 to 14 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 10 and age < 15 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 10 and age < 15 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 10 and age < 15 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age > 10 and age < 15 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 10 and age < 15 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 10 and age < 15 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 10 and age < 15 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 10 and age < 15 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 10 and age < 15 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 10 and age < 15 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '15 to 19 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 15 and age < 20 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 15 and age < 20 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 15 and age < 20 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age > 15 and age < 20 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 15 and age < 20 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 15 and age < 20 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 15 and age < 20 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 15 and age < 20 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 15 and age < 20 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 15 and age < 20 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '20 to 24 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 20 and age < 25 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 20 and age < 25 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 20 and age < 25 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age > 20 and age < 25 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 20 and age < 25 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 20 and age < 25 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 20 and age < 25 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 20 and age < 25 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 20 and age < 25 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 20 and age < 25 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '25 to 29 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 25 and age < 30 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 25 and age < 30 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 25 and age < 30 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 25 and age < 30 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 25 and age < 30 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 25 and age < 30 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 25 and age < 30 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 25 and age < 30 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 25 and age < 30 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 25 and age < 30 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '30 to 34 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 30 and age < 35 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 30 and age < 35 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 30 and age < 35 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 30 and age < 35 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 30 and age < 35 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 30 and age < 35 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 30 and age < 35 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 30 and age < 35 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 30 and age < 35 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 30 and age < 35 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '35 to 39 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 35 and age < 40 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 35 and age < 40 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 35 and age < 40 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 35 and age < 40 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 35 and age < 40 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 35 and age < 40 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 35 and age < 40 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 35 and age < 40 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 35 and age < 40 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 35 and age < 40 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '40 to 44 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 40 and age < 45 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 40 and age < 45 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 40 and age < 45 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age >= 40 and age < 45 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 40 and age < 45 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 40 and age < 45 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 40 and age < 45 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 40 and age < 45 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 40 and age < 45 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 40 and age < 45 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '45 to 49 Years' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and age >= 45 and age < 50 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and age >= 45 and age < 50 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and age >= 45 and age < 50 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and age > 45 and age < 50 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and age >= 45 and age < 50 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and age >= 45 and age < 50 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and age >= 45 and age < 50 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and age >= 45 and age < 50 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and age >= 45 and age < 50 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and age >= 45 and age < 50 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
+union all
+select '50 Years and Above' as 'Age groups' ,sex,
+count(distinct(case when pid is not null and Age >= 50 then pid end)) as 'ART patients with no clinical contact since their last expected contact',
+count(distinct(case when outcomedied is not null and Age >= 50 then pid end)) as 'Patient outcome - Died',
+count(distinct(case when outcomeselftransfer is not null and Age >= 50 then pid end)) as 'Patient outcome - Self transfer (silent transfer)',
+count(distinct(case when tracedpatientunabletolocate is not null and Age >= 50 then pid end)) as 'Patient outcome - Traced patient (unable to locate)',
+count(distinct(case when didnottrace is not null and Age >= 50 then pid end)) as 'Patient outcome - Did not attempt to trace patient',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathTB is not null and Age >= 50 then pid end)) as 'Cause of death - TB',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathCancer is not null and Age >= 50 then pid end)) as 'Cause of death - Cancer',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathOtherinfecetious is not null and Age >= 50 then pid end)) as 'Cause of death - Other infectious and parasitic disease',
+count(distinct(case when endoffollowupduetodeath is not null and causeofdeathNonNaturalCauses is not null and Age >= 50 then pid end)) as 'Cause of death - Non-natural causes (accident/war)',
+count(distinct(case when endoffollowupduetodeath is not null and causeofUnknowCause is not null and Age >= 50 then pid end)) as 'Cause of death - Unknown Cause'
+ from (
+select distinct(patient_id) as pid, end_date_time , status, voided from patient_appointment where status in ('LostToFollowUp', 'Missed') and voided = 0 and end_date_time
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tLostTofollowup
+inner join(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M') and gender is not null
+)tDemographics on tLostTofollowup.pid = tDemographics.person_id
+left join (
+select person_id, outcomeselftransfer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomeselftransfer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Self transfer(Silent Transfer)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tSelfTransfer on tLostTofollowup.pid = tSelfTransfer.person_id
+left join (
+select person_id, tracedpatientunabletolocate from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tracedpatientunabletolocate', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Traced patient (Unable to locate)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTracedPatientUnabletolocate on tLostTofollowup.pid = tTracedPatientUnabletolocate.person_id
+left join(
+select person_id, didnottrace from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'didnottrace', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Did not attempt to trace patient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDidnotattempttotrace on tLostTofollowup.pid = tDidnotattempttotrace.person_id
+left join(
+select person_id, endoffollowupduetodeath from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'endoffollowupduetodeath', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Death during treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End Of Follow Up Reason' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tEndoffollowupDeath on tLostTofollowup.pid = tEndoffollowupDeath.person_id
+left join (
+select person_id, causeofdeathTB from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathTB', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, TB' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCauseByTB on tLostTofollowup.pid = tDeathCauseByTB.person_id
+left join(
+select person_id, causeofdeathCancer from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathCancer', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Cancer' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedCancer on tLostTofollowup.pid = tDeathCausedCancer.person_id
+left join(
+select person_id, causeofdeathOtherinfecetious from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathOtherinfecetious', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Other Other infectious and parasitic disease' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedOtherInfectious on tLostTofollowup.pid = tDeathCausedOtherInfectious.person_id
+left join(
+select person_id, causeofdeathNonNaturalCauses from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofdeathNonNaturalCauses', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death, Non-natural causes (accident/war)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByNonNaturalCauses on tLostTofollowup.pid = tDeathCausedByNonNaturalCauses.person_id
+left join(
+select person_id, causeofUnknowCause from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'causeofUnknowCause', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and
+value_coded = (select concept_id from concept_name where name = 'Cause Of Death,Unknown Cause' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow-up,Cause Of Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDeathCausedByUnknownCauses on tLostTofollowup.pid = tDeathCausedByUnknownCauses.person_id
+left join(
+select person_id, outcomedied from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'outcomedied', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'Patient outcome, Death' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'End of Follow up,Patient Outcome' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0 ) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tPatientDied on tLostTofollowup.pid = tPatientDied.person_id group by sex
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/quartely_viral_load_report.sql b/openmrs/apps/reports/sql/quartely_viral_load_report.sql
new file mode 100644
index 000000000..10b976f69
--- /dev/null
+++ b/openmrs/apps/reports/sql/quartely_viral_load_report.sql
@@ -0,0 +1,526 @@
+select 'less than 1 year' as 'Age Groups', sex,
+@documented1 := count(distinct(case when value_numeric is not null and age < 1 then pid end)) as '\# of VL documented in ART',
+count(distinct(case when value_numeric >= 1000 and age < 1 then pid end)) as '\# of VL results(>=1000 copies/ml) in ART',
+count(distinct(case when value_numeric < 1000 and age < 1 then pid end)) as '\# of VL results (<1000copies/ml) in ART',
+count(distinct(case when isPregnant and age < 1 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age < 1 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age < 1 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age < 1 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id = (select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01')
+and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '1 to 4 Years' as 'Age Groups', sex,
+@documented2 := count(distinct(case when value_numeric is not null and age >= 1 and age < 5 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 1 and age < 5 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 1 and age < 5 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 1 and age < 5 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 1 and age < 5 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 1 and age < 5 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 1 and age < 5 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '5 to 9 Years' as 'Age Groups', sex,
+@documented3 := count(distinct(case when value_numeric is not null and age >= 5 and age < 10 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 5 and age < 10 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 5 and age < 10 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 5 and age < 10 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 5 and age < 10 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 5 and age < 10 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 5 and age < 10 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '10 to 14 Years' as 'Age Groups', sex,
+@documented4 := count(distinct(case when value_numeric is not null and age >= 10 and age < 15 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 10 and age < 15 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 10 and age < 15 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 10 and age < 15 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 10 and age < 15 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 10 and age < 15 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 10 and age < 15 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '15 to 19 Years' as 'Age Groups', sex,
+@documented5 := count(distinct(case when value_numeric is not null and age >= 15 and age < 20 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 15 and age < 20 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 15 and age < 20 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 15 and age < 20 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 15 and age < 20 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 15 and age < 20 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 15 and age < 20 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '20 to 24 Years' as 'Age Groups', sex,
+@documented6 := count(distinct(case when value_numeric is not null and age >= 20 and age < 25 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 20 and age < 25 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 20 and age < 25 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 20 and age < 25 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 20 and age < 25 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 20 and age < 25 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 20 and age < 25 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '25 to 29 Years' as 'Age Groups', sex,
+@documented7 := count(distinct(case when value_numeric is not null and age >= 25 and age < 30 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 25 and age < 30 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 25 and age < 30 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 25 and age < 29 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 29 and age < 30 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 29 and age < 30 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 29 and age < 30 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '30 to 34 Years' as 'Age Groups', sex,
+@documented8 := count(distinct(case when value_numeric is not null and age >= 30 and age < 35 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 30 and age < 35 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 30 and age < 35 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 30 and age < 35 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 30 and age < 35 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 30 and age < 34 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 30 and age < 35 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '35 to 39 Years' as 'Age Groups', sex,
+@documented9 := count(distinct(case when value_numeric is not null and age >= 35 and age < 40 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 35 and age < 40 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 35 and age < 40 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 35 and age < 40 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 35 and age < 40 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 35 and age < 40 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 35 and age < 40 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '40 to 44 Years' as 'Age Groups', sex,
+@documented10 := count(distinct(case when value_numeric is not null and age >= 40 and age < 45 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 40 and age < 45 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 40 and age < 45 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 40 and age < 45 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 40 and age < 45 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 40 and age < 45 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 40 and age < 45 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '45 to 49 Years' as 'Age Groups', sex,
+@documented11 := count(distinct(case when value_numeric is not null and age >= 45 and age < 50 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 45 and age < 50 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 45 and age < 50 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 45 and age < 50 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 45 and age < 50 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 45 and age < 50 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >= 45 and age < 50 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+union all
+select '50 Years and Above' as 'Age Groups', sex,
+@documented12 := count(distinct(case when value_numeric is not null and age >= 50 then pid end)) as 'Vl_Documented',
+count(distinct(case when value_numeric >= 1000 and age >= 50 then pid end)) as 'VL results (>= 1,000 copies/ml)',
+count(distinct(case when value_numeric < 1000 and age >= 50 then pid end)) as 'VL results (< 1,000 copies/ml)',
+count(distinct(case when isPregnant and age >= 50 then pid end)) as 'Pregant Women with documented VL result',
+count(distinct(case when isPregnant and value_numeric >= 1000 and age >= 50 then pid end)) as 'Pregant Women with documented VL result Above or Equal 1000',
+count(distinct(case when isBreastfeeding and sex = 'F' and age >= 50 then pid end)) as 'Breastfeeding Women with documented VL result',
+count(distinct(case when isBreastfeeding and sex = 'F' and value_numeric >= 1000 and age >=50 then pid end)) as 'Breastfeeding Women with VL result equal or above 1000'
+from
+(
+select person_id as pid, obs_datetime , value_numeric from obs where concept_id =
+(select concept_id from concept_name where name = 'VL Results' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tvlResults
+left join (
+select person_id, isPregnant from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isPregnant', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'FP Pregnant' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIspregnant on tvlResults.pid = tIspregnant.person_id
+left join (
+select person_id, isBreastfeeding from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'isBreastfeeding', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Currently Breastfeeding?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsbreastfeeding on tvlResults.pid = tIsbreastfeeding.person_id
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F','M')
+)tDemographics on tvlResults.pid = tDemographics.person_id group by sex
+
+
+
+
+
+
+
+
+
+
diff --git a/openmrs/apps/reports/sql/quarterly_art.sql b/openmrs/apps/reports/sql/quarterly_art.sql
new file mode 100644
index 000000000..221285e17
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_art.sql
@@ -0,0 +1,842 @@
+SELECT NULL AS 'Newly started on ART- Age',
+ NULL AS 'Newly started on ART- sex',
+ NULL AS '\# Newly started on ART',
+ NULL AS '\# Newly started on ART Breast feeding women on initiation',
+ NULL AS 'Currently on ART -Age',
+ NULL AS 'Currently on ART -Sex',
+ NULL AS '\# Current on ART '
+FROM DUAL
+
+UNION ALL
+
+SELECT NULL AS 'Age Groups',
+ 'Newly' AS 'SEX',
+ 'Started On' AS '\# started on ART',
+ 'ART' AS '\# of breast Feeding women at initiation',
+ 'Currently on' AS 'Age',
+ 'ART' AS 'Sex',
+ NULL AS '\# current on ART'
+FROM DUAL
+
+UNION ALL
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Age Groups',
+ year_q.year AS 'SEX',
+ NULL AS '\# started on ART',
+ NULL AS '\# of breast Feeding women at initiation',
+ 'TX_CURR ' AS 'Age',
+ ' (ART register)' AS 'Sex',
+ NULL AS '\# current on ART'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT 'Age Groups',
+ 'SEX',
+ NULL AS '\# started on ART',
+ '\# of breast Feeding women at initiation',
+ 'Age',
+ 'Sex',
+ '\# current on ART'
+FROM DUAL
+
+UNION ALL
+
+SELECT DISTINCT observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ format(sum(if(newly_started.patient_id IS NOT NULL, 1, 0)),0) AS '\# started on ART',
+ format(sum(if(breastfeeding.patient_id IS NOT NULL, 1, 0)),0) AS '\# of breast Feeding women at initiation',
+ observed_age_group.report_group_name AS 'Age',
+ observed_age_group.sex AS 'Sex',
+ format(sum(if(currently_on_art.patient_id IS NOT NULL, 1, 0)),0) AS '\# current on ART'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ UNION DISTINCT
+ SELECT pt.patient_id as val
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND obs2.voided = 0
+
+ )newly_started ON newly_started.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ UNION DISTINCT
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND obs2.voided = 0
+
+ )breastfeeding ON breastfeeding.patient_id = pt.patient_id
+ AND breastfeeding.patient_id IN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Currently Breastfeeding?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ )
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ AND pa.voided = 0
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= LAST_DAY(DATE(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))
+ AND obs2.voided = 0
+
+ )currently_on_art
+ ON currently_on_art.patient_id = pt.patient_id
+ AND currently_on_art.patient_id NOT IN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN obs obs2
+ ON obs2.person_id=pt.patient_id
+ AND obs2.concept_id =(SELECT concept_id FROM concept_view WHERE concept_full_name ='Interruption Type')
+ AND DATE(obs2.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))
+ INNER JOIN obs restarted
+ ON restarted.encounter_id = obs2.encounter_id
+ AND restarted.concept_id=(select concept_id from concept_view where concept_full_name ='Date If Restarted')
+ AND DATE(restarted.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))
+ AND restarted.voided = 0
+ INNER JOIN (
+ SELECT max(obs_id) as obs_id
+ FROM obs
+ WHERE concept_id=(SELECT concept_id FROM concept_view WHERE concept_full_name ='Date If Restarted')
+ AND DATE(obs.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))
+ GROUP BY obs.person_id
+ )obs3
+ ON obs3.obs_id = restarted.obs_id
+ AND (restarted.value_datetime is null OR DATE(restarted.value_datetime) < DATE(obs2.obs_datetime))
+ group by pt.patient_id
+ )interrupted
+ ON interrupted.patient_id = pt.patient_id
+ )
+
+
+GROUP BY observed_age_group.id
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+UNION ALL
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Age Groups',
+ year_q.year AS 'SEX',
+ NULL AS '\# started on ART',
+ NULL AS '\# of breast Feeding women at initiation',
+ 'TX_CURR ' AS 'Age',
+ ' (ART register)' AS 'Sex',
+ NULL AS '\# current on ART'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT 'Age Groups',
+ 'SEX',
+ NULL AS '\# started on ART',
+ '\# of breast Feeding women at initiation',
+ 'Age',
+ 'Sex',
+ '\# current on ART'
+FROM DUAL
+
+UNION ALL
+
+SELECT DISTINCT observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ format(sum(if(newly_started.patient_id IS NOT NULL, 1, 0)),0) AS '\# started on ART',
+ format(sum(if(breastfeeding.patient_id IS NOT NULL, 1, 0)),0) AS '\# of breast Feeding women at initiation',
+ observed_age_group.report_group_name AS 'Age',
+ observed_age_group.sex AS 'Sex',
+ format(sum(if(currently_on_art.patient_id IS NOT NULL, 1, 0)),0) AS '\# current on ART'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ UNION DISTINCT
+ SELECT pt.patient_id as val
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND obs2.voided = 0
+
+ )newly_started ON newly_started.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ UNION DISTINCT
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND obs2.voided = 0
+
+ )breastfeeding ON breastfeeding.patient_id = pt.patient_id
+ AND breastfeeding.patient_id IN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Currently Breastfeeding?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ )
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ AND pa.voided = 0
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= DATE(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))
+ AND obs2.voided = 0
+
+ )currently_on_art
+ ON currently_on_art.patient_id = pt.patient_id
+ AND currently_on_art.patient_id NOT IN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN obs obs2
+ ON obs2.person_id=pt.patient_id
+ AND obs2.concept_id =(SELECT concept_id FROM concept_view WHERE concept_full_name ='Interruption Type')
+ AND DATE(obs2.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))
+ INNER JOIN obs restarted
+ ON restarted.encounter_id = obs2.encounter_id
+ AND restarted.concept_id=(select concept_id from concept_view where concept_full_name ='Date If Restarted')
+ AND DATE(restarted.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))
+ AND restarted.voided = 0
+ INNER JOIN (
+ SELECT max(obs_id) as obs_id
+ FROM obs
+ WHERE concept_id=(SELECT concept_id FROM concept_view WHERE concept_full_name ='Date If Restarted')
+ AND DATE(obs.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))
+ GROUP BY obs.person_id
+ )obs3
+ ON obs3.obs_id = restarted.obs_id
+ AND (restarted.value_datetime is null OR DATE(restarted.value_datetime) < DATE(obs2.obs_datetime))
+ group by pt.patient_id
+ )interrupted
+ ON interrupted.patient_id = pt.patient_id
+ )
+
+
+GROUP BY observed_age_group.id
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Age Groups',
+ year_q.year AS 'SEX',
+ NULL AS '\# started on ART',
+ NULL AS '\# of breast Feeding women at initiation',
+ 'TX_CURR ' AS 'Age',
+ ' (ART register)' AS 'Sex',
+ NULL AS '\# current on ART'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT 'Age Groups',
+ 'SEX',
+ NULL AS '\# started on ART',
+ '\# of breast Feeding women at initiation',
+ 'Age',
+ 'Sex',
+ '\# current on ART'
+FROM DUAL
+
+UNION ALL
+
+SELECT DISTINCT observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ format(sum(if(newly_started.patient_id IS NOT NULL, 1, 0)),0) AS '\# started on ART',
+ format(sum(if(breastfeeding.patient_id IS NOT NULL, 1, 0)),0) AS '\# of breast Feeding women at initiation',
+ observed_age_group.report_group_name AS 'Age',
+ observed_age_group.sex AS 'Sex',
+ format(sum(if(currently_on_art.patient_id IS NOT NULL, 1, 0)),0) AS '\# current on ART'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ UNION DISTINCT
+ SELECT pt.patient_id as val
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND obs2.voided = 0
+
+ )newly_started ON newly_started.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ UNION DISTINCT
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND obs2.voided = 0
+
+ )breastfeeding ON breastfeeding.patient_id = pt.patient_id
+ AND breastfeeding.patient_id IN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Currently Breastfeeding?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ )
+
+ LEFT JOIN (
+ SELECT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ AND pa.voided = 0
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= DATE(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ AND obs2.voided = 0
+
+ )currently_on_art
+ ON currently_on_art.patient_id = pt.patient_id
+ AND currently_on_art.patient_id NOT IN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided=0 AND pt.voided=0
+ INNER JOIN (
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN obs obs2
+ ON obs2.person_id=pt.patient_id
+ AND obs2.concept_id =(SELECT concept_id FROM concept_view WHERE concept_full_name ='Interruption Type')
+ AND DATE(obs2.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ INNER JOIN obs restarted
+ ON restarted.encounter_id = obs2.encounter_id
+ AND restarted.concept_id=(select concept_id from concept_view where concept_full_name ='Date If Restarted')
+ AND DATE(restarted.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ AND restarted.voided = 0
+ INNER JOIN (
+ SELECT max(obs_id) as obs_id
+ FROM obs
+ WHERE concept_id=(SELECT concept_id FROM concept_view WHERE concept_full_name ='Date If Restarted')
+ AND DATE(obs.obs_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ GROUP BY obs.person_id
+ )obs3
+ ON obs3.obs_id = restarted.obs_id
+ AND (restarted.value_datetime is null OR DATE(restarted.value_datetime) < DATE(obs2.obs_datetime))
+ group by pt.patient_id
+ )interrupted
+ ON interrupted.patient_id = pt.patient_id
+ )
+
+
+GROUP BY observed_age_group.id
+
+
diff --git a/openmrs/apps/reports/sql/quarterly_index_sheet.sql b/openmrs/apps/reports/sql/quarterly_index_sheet.sql
new file mode 100644
index 000000000..5c3671275
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_index_sheet.sql
@@ -0,0 +1,2492 @@
+select 'Less than 1 Year' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge < 1 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge < 1 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge < 1 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge < 1 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge < 1 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge < 1 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge < 1 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '1 - 4 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 1 and ContactsAge < 5 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+union all
+
+select '5 - 9 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 5 and ContactsAge < 10 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '10 - 14 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 10 and ContactsAge < 15 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '15 - 19 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 15 and ContactsAge < 20 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '20 - 24 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 20 and ContactsAge < 25 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+union all
+
+select '25 - 29 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 25 and ContactsAge < 30 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+
+union all
+
+select '30 - 34 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 30 and ContactsAge < 35 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+
+union all
+
+select '35 - 39 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 35 and ContactsAge < 40 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+union all
+
+select '40 - 44 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 40 and ContactsAge < 45 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '45 - 49 Years' as 'Age group',PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 45 and ContactsAge < 50 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+union all
+
+select '50 Years and Above' as 'Age group', PatnerGender as 'Sex',
+count(distinct(case when Names is not null and ContactsAge >= 50 then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 50 and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null and ContactsAge >= 50 then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and ContactsAge >= 50 and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and ContactsAge >= 50 and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and ContactsAge >= 50 and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and ContactsAge >= 50 and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+union all
+
+select 'Totals' as 'Age group', PatnerGender as 'Sex',
+count(distinct(case when Names is not null then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b group by PatnerGender
+
+
+union all
+
+select 'Total All' as 'Age group', PatnerGender as 'Sex',
+count(distinct(case when Names is not null then Names end)) as 'Number of Index cases offered index testing services',
+count(distinct(case when Names is not null and wasContactTested = 'YES' then Names end)) as 'Number of index cases that accepted index testing services',
+count(distinct(case when Names is not null then Names end)) as 'Number of contacts elicited (brought)',
+count(distinct(case when Names is not null and newHivResults = 'Negative' then Names end)) as 'New Negative',
+count(distinct(case when Names is not null and newHivResults = 'Positive' then Names end)) as 'New Positive',
+count(distinct(case when Names is not null and KnownPositiveResults = 'Positive' then Names end)) as 'Known Positive',
+count(distinct(case when Names is not null and (wasContactTested = 'NO' or wasContactTested is null) then Names end)) as 'Not Tested'
+from (
+select ClientName as 'IndexName' , artnumber , ContactsAge , Age , sex , Names ,wasContactTested,
+(case when PatnerGender = (select concept_id from concept_name where name = 'Male' and concept_name_type = 'FULLY_SPECIFIED') then 'M' else 'F' end) as 'PatnerGender'
+, isHivStatusKnown , newHivResults , KnownPositiveResults
+ from (
+select person_id as 'pid' , value as 'newpatientid' from person_attribute where person_attribute_type_id = (SELECT person_attribute_type_id FROM openmrs.person_attribute_type where name = 'TypeofPatient'
+)and value =(select concept_id from concept_name where name = 'NewPatient' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)tNewPatient
+inner join (
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tDemographics on tNewPatient.pid = tDemographics.person_id
+inner join (
+select pid ,
+(case when sexual_partner = 'YES' then sexual_partner_names else family_member_names end) as 'Names',
+(case when sexual_partner = 'YES' then sexual_partner_age else family_partner_age end) as 'ContactsAge',
+(case when sexual_partner = 'YES' then sexualPartnerTested else familyMemberTested end) as 'wasContactTested',
+(case when sexual_partner = 'YES' then sexual_partner_sex else family_partner_sex end) as 'PatnerGender',
+(case when sexual_partner = 'YES' then sexualPartnerKnownHiv else familyMemberKnownHiv end) as 'isHivStatusKnown',
+(case when sexual_partner = 'YES' then sexual_partner_hts_result else family_member_hts_result end) as 'newHivResults',
+(case when sexual_partner = 'YES' then sexual_partner_known_positives else family_known_positives end) as 'KnownPositiveResults'
+from (
+select person_id as pid , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = '1' then 'YES' else 'No' end) as 'sexual_partner'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualRelationship
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'sexual_partner_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual partner names' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerNames on tSexualRelationship.obs_group_id = tSexualPartnerNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_text as 'family_member_names'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member names' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberNames on tSexualRelationship.obs_group_id = tFamilyMemberNames.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'sexual_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerAge on tSexualRelationship.obs_group_id = tSexualPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_numeric as 'family_partner_age'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Age' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyPartnerAge on tSexualRelationship.obs_group_id = tFamilyPartnerAge.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'family_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberSex on tSexualRelationship.obs_group_id = tFamilyMemberSex.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+value_coded as 'sexual_partner_sex'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Sex' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerGender on tSexualRelationship.obs_group_id = tSexualPartnerGender.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'NO' end ) as 'familyMemberKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnowStatus on tSexualRelationship.obs_group_id = tFamilyMemberKnowStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED')
+ then 'Known' else 'NO' end ) as 'sexualPartnerKnownHiv'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownHivStatus on tSexualRelationship.obs_group_id = tSexualPartnerKnownHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Known' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Known' else 'UnKnown' end ) as 'familyMemberKnowHivStatus'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Family Member - HIV Status' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberHivStatus on tSexualRelationship.obs_group_id = tFamilyMemberHivStatus.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'family_member_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyResultsHTS on tSexualRelationship.obs_group_id = tFamilyResultsHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_hts_result'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - Result of HTS' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerHTS on tSexualRelationship.obs_group_id = tSexualPartnerHTS.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'NO' end ) as 'family_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberKnownPostive on tSexualRelationship.obs_group_id = tFamilyMemberKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = (select concept_id from concept_name where name = 'Positive' and concept_name_type = 'FULLY_SPECIFIED'
+) then 'Positive' else 'Negative' end ) as 'sexual_partner_known_positives'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Sexual Partner - HIV Result' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerKnownPostive on tSexualRelationship.obs_group_id = tSexualPartnerKnownPostive.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'sexualPartnerTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Sexual Partner Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+ and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tSexualPartnerTested on tSexualRelationship.obs_group_id = tSexualPartnerTested.obs_group_id
+left join (
+select person_id , encounter_id , obs_datetime , obs_group_id ,
+(case when value_coded = 1 then 'YES' else 'NO' end ) as 'familyMemberTested'
+from obs o
+where concept_id = (select concept_id from concept_name where name = 'Was Family Member Contact Tested?' and concept_name_type = 'FULLY_SPECIFIED')
+and voided = 0 and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+)tFamilyMemberTested on tSexualRelationship.obs_group_id = tFamilyMemberTested.obs_group_id
+)tContacts on tDemographics.person_id = tContacts.pid
+)b
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/openmrs/apps/reports/sql/quarterly_pmtct_anc.sql b/openmrs/apps/reports/sql/quarterly_pmtct_anc.sql
new file mode 100644
index 000000000..ddfa61ce6
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_pmtct_anc.sql
@@ -0,0 +1,805 @@
+SELECT "" AS 'Testing point',
+ CONCAT('Reporting Period : ',quarter.month,' ',year_q.year) 'Age Groups',
+ '' AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ '' AS '\# of known HIV positives at entry',
+ '' AS '\# tested in the reporting period',
+ '' AS '\# with Known HIV status ',
+ '' AS '\# of newly tested HIV postive ',
+ '' AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ '' AS '\# with unknown HIV status\# not tested for HIV)',
+ '' AS '\# of new negatives'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL
+FROM DUAL
+
+UNION ALL
+
+
+SELECT DISTINCT if(observed_age_group.name = '25-29 yr M', 'PMTCT_STAT (ANC 1)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(newly_attended.patient_id IS NOT NULL, 1, 0)),0) AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ format(sum(if(known_positives_entry.patient_id IS NOT NULL, 1, 0)),0) AS '\# of known HIV positives at entry',
+ format(sum(if(tested_in_period.patient_id IS NOT NULL, 1, 0)),0) AS '\# tested in the reporting period',
+ format(sum(if(known_status.patient_id IS NOT NULL, 1, 0)),0) AS '\# with Known HIV status ',
+ format(sum(if(newly_tested_positive.patient_id IS NOT NULL, 1, 0)),0) AS '\# of newly tested HIV postive ',
+ format(sum(if(total_positive.patient_id IS NOT NULL, 1, 0)),0) AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ format(sum(if(unknown_status.patient_id IS NOT NULL, 1, 0)),0)AS '\# with unknown HIV status\# not tested for HIV)',
+ format(sum(if(newly_tested_negative.patient_id IS NOT NULL, 1, 0)),0) AS '\# of new negatives'
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ )newly_attended ON newly_attended.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs pregnant
+ ON pregnant.encounter_id = e2.encounter_id
+ AND pregnant.voided=0
+ AND pregnant.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(pregnant.value_datetime) < DATE(e.encounter_datetime)
+ )known_positives_entry ON known_positives_entry.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded IS NOT NULL
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ )tested_in_period ON tested_in_period.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ UNION DISTINCT
+
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Known')
+ AND e2.encounter_datetime <= e.encounter_datetime
+
+ )known_status ON known_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ )newly_tested_positive ON newly_tested_positive.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ UNION DISTINCT
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ )total_positive ON total_positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Unkown/Not tested')
+ AND e2.encounter_datetime <= e.encounter_datetime
+ )unknown_status ON unknown_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Negative')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ )newly_tested_negative ON newly_tested_negative.patient_id = pt.patient_id where observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr F','5-9 yr M','Total M','Total F')
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL
+FROM DUAL
+UNION ALL
+
+SELECT "" AS 'Testing point',
+ CONCAT('Reporting Period : ',quarter.month,' ',year_q.year) 'Age Groups',
+ '' AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ '' AS '\# of known HIV positives at entry',
+ '' AS '\# tested in the reporting period',
+ '' AS '\# with Known HIV status ',
+ '' AS '\# of newly tested HIV postive ',
+ '' AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ '' AS '\# with unknown HIV status\# not tested for HIV)',
+ '' AS '\# of new negatives'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL
+FROM DUAL
+UNION ALL
+
+SELECT DISTINCT if(observed_age_group.name = '25-29 yr M', 'PMTCT_STAT (ANC 1)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(newly_attended.patient_id IS NOT NULL, 1, 0)),0) AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ format(sum(if(known_positives_entry.patient_id IS NOT NULL, 1, 0)),0) AS '\# of known HIV positives at entry',
+ format(sum(if(tested_in_period.patient_id IS NOT NULL, 1, 0)),0) AS '\# tested in the reporting period',
+ format(sum(if(known_status.patient_id IS NOT NULL, 1, 0)),0) AS '\# with Known HIV status ',
+ format(sum(if(newly_tested_positive.patient_id IS NOT NULL, 1, 0)),0) AS '\# of newly tested HIV postive ',
+ format(sum(if(total_positive.patient_id IS NOT NULL, 1, 0)),0) AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ format(sum(if(unknown_status.patient_id IS NOT NULL, 1, 0)),0)AS '\# with unknown HIV status\# not tested for HIV)',
+ format(sum(if(newly_tested_negative.patient_id IS NOT NULL, 1, 0)),0) AS '\# of new negatives'
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ )newly_attended ON newly_attended.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs pregnant
+ ON pregnant.encounter_id = e2.encounter_id
+ AND pregnant.voided=0
+ AND pregnant.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(pregnant.value_datetime) < DATE(e.encounter_datetime)
+ )known_positives_entry ON known_positives_entry.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded IS NOT NULL
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ )tested_in_period ON tested_in_period.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ UNION DISTINCT
+
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Known')
+ AND e2.encounter_datetime <= e.encounter_datetime
+
+ )known_status ON known_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ )newly_tested_positive ON newly_tested_positive.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ UNION DISTINCT
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ )total_positive ON total_positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Unkown/Not tested')
+ AND e2.encounter_datetime <= e.encounter_datetime
+ )unknown_status ON unknown_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Negative')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ )newly_tested_negative ON newly_tested_negative.patient_id = pt.patient_id
+ where observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr F','5-9 yr M','Total M','Total F')
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL
+FROM DUAL
+UNION ALL
+
+SELECT "" AS 'Testing point',
+ CONCAT('Reporting Period : ',quarter.month,' ',year_q.year) 'Age Groups',
+ '' AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ '' AS '\# of known HIV positives at entry',
+ '' AS '\# tested in the reporting period',
+ '' AS '\# with Known HIV status ',
+ '' AS '\# of newly tested HIV postive ',
+ '' AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ '' AS '\# with unknown HIV status\# not tested for HIV)',
+ '' AS '\# of new negatives'
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as year
+ )year_q
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL , NULL
+FROM DUAL
+UNION ALL
+
+SELECT DISTINCT if(observed_age_group.name = '25-29 yr M', 'PMTCT_STAT (ANC 1)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(newly_attended.patient_id IS NOT NULL, 1, 0)),0) AS '\# of pregnant woman newly attended ANC (ANC 1)',
+ format(sum(if(known_positives_entry.patient_id IS NOT NULL, 1, 0)),0) AS '\# of known HIV positives at entry',
+ format(sum(if(tested_in_period.patient_id IS NOT NULL, 1, 0)),0) AS '\# tested in the reporting period',
+ format(sum(if(known_status.patient_id IS NOT NULL, 1, 0)),0) AS '\# with Known HIV status ',
+ format(sum(if(newly_tested_positive.patient_id IS NOT NULL, 1, 0)),0) AS '\# of newly tested HIV postive ',
+ format(sum(if(total_positive.patient_id IS NOT NULL, 1, 0)),0) AS 'Total \# of HIV postives (new + Previuosly known postives )',
+ format(sum(if(unknown_status.patient_id IS NOT NULL, 1, 0)),0)AS '\# with unknown HIV status\# not tested for HIV)',
+ format(sum(if(newly_tested_negative.patient_id IS NOT NULL, 1, 0)),0) AS '\# of new negatives'
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ )newly_attended ON newly_attended.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Visit Number')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='1 = First Contact')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs pregnant
+ ON pregnant.encounter_id = e2.encounter_id
+ AND pregnant.voided=0
+ AND pregnant.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(pregnant.value_datetime) < DATE(e.encounter_datetime)
+ )known_positives_entry ON known_positives_entry.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded IS NOT NULL
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ )tested_in_period ON tested_in_period.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ UNION DISTINCT
+
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Known')
+ AND e2.encounter_datetime <= e.encounter_datetime
+
+ )known_status ON known_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ )newly_tested_positive ON newly_tested_positive.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Positive')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ UNION DISTINCT
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND DATE(tested.value_datetime) < DATE(e.encounter_datetime)
+ )total_positive ON total_positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ AND MONTH(obs.obs_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs.obs_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs screening
+ ON screening.encounter_id = e2.encounter_id
+ AND screening.voided=0
+ AND screening.concept_id = (select concept_id from concept_view where concept_full_name ='TB Screening - HIV Status')
+ AND screening.value_coded = (select concept_id from concept_view where concept_full_name ='Unkown/Not tested')
+ AND e2.encounter_datetime <= e.encounter_datetime
+ )unknown_status ON unknown_status.patient_id = pt.patient_id
+ LEFT JOIN(
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND obs.value_text IS NOT NULL
+ INNER JOIN encounter e2
+ ON e2.patient_id = pt.patient_id
+ INNER JOIN obs tested
+ ON tested.encounter_id = e2.encounter_id
+ AND tested.voided=0
+ AND tested.concept_id = (select concept_id from concept_view where concept_full_name ='HIV Sample')
+ AND tested.value_coded = (select concept_id from concept_view where concept_full_name ='Negative')
+ AND MONTH(e2.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e2.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ )newly_tested_negative ON newly_tested_negative.patient_id = pt.patient_id
+ where observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr F','5-9 yr M','Total M','Total F')
+ GROUP BY observed_age_group.id
diff --git a/openmrs/apps/reports/sql/quarterly_pmtct_art.sql b/openmrs/apps/reports/sql/quarterly_pmtct_art.sql
new file mode 100644
index 000000000..2826ef169
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_pmtct_art.sql
@@ -0,0 +1,962 @@
+SELECT NULL AS 'Reporting Point',
+ NULL AS 'Age Groups',
+ NULL AS 'Total',
+ NULL AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM DUAL
+
+UNION ALL
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Reporting Point',
+ year_q.year AS 'Age Groups',
+ NULL AS 'Total',
+ NULL AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))) as year
+ )year_q
+UNION ALL
+
+
+SELECT NULL AS 'Reporting Point',
+ NULL AS 'Age Groups',
+ NULL AS 'Total',
+ 'Maternal Regimen Type' AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM DUAL
+
+UNION ALL
+
+
+SELECT
+ NULL AS 'Reporting Point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(total.patient_id IS NOT NULL, 1, 0)),0) AS 'Total',
+ format(sum(if(pregnant_newly_started_art.patient_id IS NOT NULL, 1, 0)),0) AS ' Newly initiated on ART during the current pregnancy ',
+ format(sum(if(already_art_before_pregnncy.patient_id IS NOT NULL, 1, 0)),0) AS 'Already on ART at the beginning of the current pregnancy '
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND observed_age_group.sex ='M'
+ AND observed_age_group.report_group_name != 'Total M' AND observed_age_group.report_group_name != 'Total F'
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is on ART(started AT + current on ART)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+
+ UNION distinct
+ -- New patient currently on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= DATE(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+ -- Existing patient current on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH))
+ AND obs2.voided = 0
+ )on_art ON on_art.patient_id = pt.patient_id
+ )total ON total.patient_id = pt.patient_id
+ LEFT JOIN (
+ -- Pregnant women newly started ART and in PMTCT(Has ANC number)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started > DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )pregnant_newly_started_art ON pregnant_newly_started_art.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is enrolled at ART before start of current pregnancy)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 0 MONTH)))
+ INNER JOIN encounter pregnant
+ ON pregnant.patient_id = pt.patient_id
+ INNER JOIN obs edd
+ ON edd.encounter_id = e.encounter_id
+ AND edd.voided=0
+ AND edd.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND edd.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started < DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )already_art_before_pregnncy ON already_art_before_pregnncy.patient_id = pt.patient_id where
+ observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr M','5-9 yr F','< 10 yr M','10-14 yr M','Total F') and observed_age_group.sex <> 'M'
+GROUP BY observed_age_group.id
+
+UNION ALL
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Reporting Point',
+ year_q.year AS 'Age Groups',
+ NULL AS 'Total',
+ NULL AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))) as year
+ )year_q
+UNION ALL
+
+
+SELECT NULL AS 'Reporting Point',
+ NULL AS 'Age Groups',
+ NULL AS 'Total',
+ 'Maternal Regimen Type' AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM DUAL
+
+UNION ALL
+SELECT
+ NULL AS 'Reporting Point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(total.patient_id IS NOT NULL, 1, 0)),0) AS 'Total',
+ format(sum(if(pregnant_newly_started_art.patient_id IS NOT NULL, 1, 0)),0) AS ' Newly initiated on ART during the current pregnancy ',
+ format(sum(if(already_art_before_pregnncy.patient_id IS NOT NULL, 1, 0)),0) AS 'Already on ART at the beginning of the current pregnancy '
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND observed_age_group.sex ='M'
+ AND observed_age_group.report_group_name != 'Total M' AND observed_age_group.report_group_name != 'Total F'
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is on ART(started AT + current on ART)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+
+ UNION distinct
+ -- New patient currently on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= DATE(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+ -- Existing patient current on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH))
+ AND obs2.voided = 0
+ )on_art ON on_art.patient_id = pt.patient_id
+ )total ON total.patient_id = pt.patient_id
+ LEFT JOIN (
+ -- Pregnant women newly started ART and in PMTCT(Has ANC number)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started > DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )pregnant_newly_started_art ON pregnant_newly_started_art.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is enrolled at ART before start of current pregnancy)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 1 MONTH)))
+ INNER JOIN encounter pregnant
+ ON pregnant.patient_id = pt.patient_id
+ INNER JOIN obs edd
+ ON edd.encounter_id = e.encounter_id
+ AND edd.voided=0
+ AND edd.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND edd.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started < DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )already_art_before_pregnncy ON already_art_before_pregnncy.patient_id = pt.patient_id
+ where
+ observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr M','5-9 yr F','< 10 yr M','10-14 yr M','Total F') and observed_age_group.sex <> 'M'
+
+GROUP BY observed_age_group.id
+
+
+UNION ALL
+
+
+SELECT CONCAT('Reporting Month : ',quarter.month) AS 'Reporting Point',
+ year_q.year AS 'Age Groups',
+ NULL AS 'Total',
+ NULL AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM (
+ SELECT MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as month) quarter
+ JOIN (SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as year
+ )year_q
+UNION ALL
+
+
+SELECT NULL AS 'Reporting Point',
+ NULL AS 'Age Groups',
+ NULL AS 'Total',
+ 'Maternal Regimen Type' AS ' Newly initiated on ART during the current pregnancy ',
+ NULL AS 'Already on ART at the beginning of the current pregnancy '
+FROM DUAL
+UNION ALL
+
+
+SELECT
+ NULL AS 'Reporting Point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ format(sum(if(total.patient_id IS NOT NULL, 1, 0)),0) AS 'Total',
+ format(sum(if(pregnant_newly_started_art.patient_id IS NOT NULL, 1, 0)),0) AS ' Newly initiated on ART during the current pregnancy ',
+ format(sum(if(already_art_before_pregnncy.patient_id IS NOT NULL, 1, 0)),0) AS 'Already on ART at the beginning of the current pregnancy '
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND observed_age_group.sex ='M'
+ AND observed_age_group.report_group_name != 'Total M' AND observed_age_group.report_group_name != 'Total F'
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is on ART(started AT + current on ART)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+
+ UNION distinct
+ -- New patient currently on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ INNER JOIN (
+ SELECT max(orders.order_id), max(orders.date_created) as date_created, orders.patient_id FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE DATE(orders.date_created) <= DATE(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )max_order
+ ON max_order.patient_id = pt.patient_id
+
+ UNION DISTINCT
+ -- Existing patient current on ART
+ SELECT DISTINCT pt.patient_id
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND DATE(obs2.value_datetime) <= LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ AND obs2.voided = 0
+ )on_art ON on_art.patient_id = pt.patient_id
+ )total ON total.patient_id = pt.patient_id
+ LEFT JOIN (
+ -- Pregnant women newly started ART and in PMTCT(Has ANC number)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+ AND MONTH(od.date_created) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(od.date_created) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ AND MONTH(obs2.value_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(obs2.value_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started > DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )pregnant_newly_started_art ON pregnant_newly_started_art.patient_id = pt.patient_id
+
+ LEFT JOIN (
+ -- IN PMTCT (Has ANC number) and is enrolled at ART before start of current pregnancy)
+ SELECT DISTINCT
+ pt.patient_id AS patient_id
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0
+ AND obs.concept_id = (select concept_id from concept_view where concept_full_name ='ANC No')
+ AND MONTH(e.encounter_datetime) = MONTH(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ AND YEAR(e.encounter_datetime) = YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH)))
+ INNER JOIN encounter pregnant
+ ON pregnant.patient_id = pt.patient_id
+ INNER JOIN obs edd
+ ON edd.encounter_id = e.encounter_id
+ AND edd.voided=0
+ AND edd.concept_id = (select concept_id from concept_view where concept_full_name ='EDD')
+ AND edd.value_datetime IS NOT NULL
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.concept_id = (select concept_id from concept_view where concept_full_name ='Present Pregnancy')
+ INNER JOIN (
+ -- New patient started ART
+ SELECT DISTINCT pt.patient_id, od.date_created as date_started
+ FROM patient pt
+ INNER JOIN orders od
+ ON od.patient_id = pt.patient_id
+ AND pt.voided = 0
+ AND od.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = pt.patient_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='NewPatient')
+ INNER JOIN order_type ot
+ ON ot.order_type_id = od.order_type_id
+ AND ot.order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ AND od.date_stopped IS NULL
+ AND od.order_id IN (
+ SELECT MIN(order_id) FROM orders
+ INNER JOIN drug
+ ON orders.concept_id = drug.concept_id
+ AND drug.dosage_form = (select concept_id from concept_view where concept_full_name='HIVTC, ART Regimen')
+ WHERE date_stopped IS NULL
+ AND order_type_id = (select order_type_id as ot_id from order_type where name ='Drug Order')
+ GROUP BY patient_id
+ )
+
+ UNION DISTINCT
+ -- Existing patient started ART
+ SELECT DISTINCT pt.patient_id , obs2.value_datetime as date_started
+ FROM patient pt
+ INNER JOIN person p
+ ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN person_attribute pa
+ ON pa.person_id = p.person_id
+ AND pa.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='TypeofPatient')
+ AND pa.value = (select concept_id from concept_view where concept_full_name='ExistingPatient')
+ INNER JOIN encounter e
+ ON e.patient_id = p.person_id
+ AND e.voided = 0
+ INNER JOIN obs
+ ON obs.encounter_id = e.encounter_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Were ARVS Received?')
+ AND obs.value_coded = 1
+ AND obs.voided = 0
+ INNER JOIN obs obs2
+ ON obs2.encounter_id = e.encounter_id
+ AND obs2.voided=0 AND obs2.concept_id IN (select concept_id from concept_view where concept_full_name ='ANC, ART Start Date')
+ )started_art ON started_art.patient_id = pt.patient_id AND started_art.date_started < DATE_SUB(obs.value_datetime, INTERVAL 9 MONTH)
+ )already_art_before_pregnncy ON already_art_before_pregnncy.patient_id = pt.patient_id
+ where
+ observed_age_group.name not in ('<1 yr M','<1 yr F','1-4 yr M','1-4 yr F','5-9 yr M','5-9 yr F','< 10 yr M','10-14 yr M','Total F') and observed_age_group.sex <> 'M'
+GROUP BY observed_age_group.id
diff --git a/openmrs/apps/reports/sql/quarterly_pmtct_eid.sql b/openmrs/apps/reports/sql/quarterly_pmtct_eid.sql
new file mode 100644
index 000000000..cb652ed1f
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_pmtct_eid.sql
@@ -0,0 +1,119 @@
+select @a:=@a+1 as 'Serial Number', dateSampleCollectedFirstPCR as 'Date DBS sample collected' ,HEI_Number as 'EID Number', Sex ,
+(case when enrolledatArtClinic = 'TRUE' THEN (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) else 'N/A' end) as 'Age at enrolment(Months)',
+(case when (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) <= 2 then '1' when (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) is null then 'N/A' else '0' end) as 'Age of child at first DBS sample collection (put 1 where the age belongs)\n0-≤2 months of age' ,
+(case when (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) > 2 and (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) <= 12 then '1' when (TIMESTAMPDIFF(MONTH,birthdate,enrollmentdateatart)) is null then 'N/A' else '0' end) as 'Age of child at first DBS sample collection (put 1 where the age belongs)\n2-12 months of age',
+dateResultRecivedinFacility as 'Date result was delivered to the facility' ,
+(case when infantStatus = 'Negative' then '0' when infantStatus = 'Positive' then '1' else '2' end) as 'HIV Status \n(0=Negative 1=Positive ,2=Unknown)' ,
+dateResultGivenToCaregiver as 'Date result given to the parent/care giver',
+(case when infantStatus = 'Positive' and finalstatusforhippositives = 'Referred To ART Clinic' then '1' when infantStatus = 'Positive' and finalstatusforhippositives = 'Died' then '2' when infantStatus = 'Positive' and finalstatusforhippositives = 'Lost' then '3' when infantStatus = 'Positive' and finalstatusforhippositives = 'Unknown' then '4' else 'N/A' end) as 'Linkage status for HIV positives/n(1. Linked to ART; 2 Died; 3. TO ;4.Unknown)',
+HEI_Number as 'Unique ART'
+from (
+select * from (
+select person_id, (SELECT @a:= 0) AS a , concept_id, value_datetime as 'dateSampleCollectedFirstPCR' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Sample Dispatched to PHL(First PCR Test)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Sample Dispatched to PHL(First PCR Test)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateSampleCollectedFirstPCR
+inner join(
+select pa.person_id , pa.value as 'HEI_Number' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age' , p.birthdate
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'HIVExposedInfant(HEI)No')
+and floor(datediff('#endDate#',p.birthdate) / 365) < 1
+)tHeiDemographics on tDateSampleCollectedFirstPCR.person_id = tHeiDemographics.person_id
+left join (
+select person_id as pid ,enrollmentdateatart from (
+select person_id, concept_id, value_datetime as 'enrollmentdateatart' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Date' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tHeiEnrollmentDate on tDateSampleCollectedFirstPCR.person_id = tHeiEnrollmentDate.pid
+left join (
+select pid , tConceptname.name as 'enrolledatArtClinic' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Treatment - Enrolled AT ART Clinic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)isHeiEnrolledInART on tDateSampleCollectedFirstPCR.person_id = isHeiEnrolledInART.pid
+left join (
+select * from (
+select person_id, concept_id, value_datetime as 'dateResultRecivedinFacility' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'First PCR,Date results delivered to facility' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'First PCR,Date results delivered to facility' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateResultsReceivedFacility on tDateSampleCollectedFirstPCR.person_id = tDateResultsReceivedFacility.person_id
+left join (
+select distinct(person_b) as 'mother_id' , relationship , person_a as 'hei_id' from relationship where
+relationship = (select relationship_type_id from relationship_type where a_is_to_b = 'Mother' and retired = 0) and voided = 0
+)tHeiToMotherRelationship on tDateSampleCollectedFirstPCR.person_id = tHeiToMotherRelationship.hei_id
+left join (
+select pid , tConceptname.name as 'infantStatus' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = "Infant HIV Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Infant HIV Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tInfantStatus on tHeiToMotherRelationship.mother_id = tInfantStatus.pid
+left join(
+select * from (
+select person_id, concept_id, value_datetime as 'dateResultGivenToCaregiver' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'HEI Testing (First PCR Date Result Given to Caregiver)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tResultsGivenToCareGiver on tDateSampleCollectedFirstPCR.person_id = tResultsGivenToCareGiver.person_id
+left join(
+select pid , tConceptname.name as 'finalstatusforhippositives' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = "Final Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = "Final Status" and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tInfantLinkageForHivpositives on tDateSampleCollectedFirstPCR.person_id = tInfantLinkageForHivpositives.pid
+
diff --git a/openmrs/apps/reports/sql/quarterly_pmtct_fo.sql b/openmrs/apps/reports/sql/quarterly_pmtct_fo.sql
new file mode 100644
index 000000000..f8037378b
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_pmtct_fo.sql
@@ -0,0 +1,57 @@
+SELECT CONCAT('Reporting Month : ',CONCAT(quarter.start_mon, '-' , quarter.month)) AS 'Serial \#',
+ year_q.year AS 'Date of birth',
+ NULL AS 'EID Number',
+ NULL AS 'Sex',
+ NULL AS 'Date EID sample collected' ,
+ NULL AS '0 - 2 months of age',
+ NULL AS ' 2-12 months of age',
+ NULL AS 'Final outcome at 24 months of age (1. HIV infected; 2- HIV-uninfected; 3-HIV final status unknown;4-Died without status known:'
+FROM (
+ SELECT MONTHNAME(DATE_SUB('#startDate#', INTERVAL DAYOFMONTH('#startDate#')-1 DAY)) as start_mon,
+ MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as month) quarter
+ JOIN (
+ SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as year
+ )year_q
+
+
+UNION ALL
+
+SELECT NULL AS 'Serial \#',
+ DATE_FORMAT(p.birthdate, "%d/%m/%Y")AS 'Date of birth',
+ hei_no.value AS 'EID Number',
+ p.gender AS 'Sex',
+ DATE_FORMAT(date_sample_collected.value_datetime, "%d/%m/%Y") AS 'Date EID sample collected' ,
+ IF(eid_age.value_numeric IS NOT NULL, IF(eid_age.value_numeric <=2, 1, ''),
+ IF(date_sample_collected.value_datetime IS NOT NULL AND TIMESTAMPDIFF( MONTH, p.birthdate, date_sample_collected.value_datetime) <=2 , 1 , '')) AS '0 - 2 months of age',
+ IF(eid_age.value_numeric IS NOT NULL, IF(eid_age.value_numeric BETWEEN 3 AND 12 , 1, ''),
+ IF(date_sample_collected.value_datetime IS NOT NULL AND TIMESTAMPDIFF( MONTH, p.birthdate, date_sample_collected.value_datetime) BETWEEN 3 AND 12 , 1 , '')) AS ' 2-12 months of age',
+ CASE
+ WHEN outcome.value_coded = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= '24Months Outcome,HIV infected') THEN 1
+ WHEN outcome.value_coded = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= '24Months Outcome,HIV uninfected') THEN 2
+ WHEN outcome.value_coded = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= '24Months Outcome,HIV Final Status Unknown') THEN 3
+ WHEN outcome.value_coded = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= '24Months Outcome,Died without status known') THEN 4
+ END
+ AS 'Final outcome at 24 months of age (1. HIV infected; 2- HIV-uninfected; 3-HIV final status unknown;4-Died without status known:'
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ AND p.birthdate BETWEEN DATE_SUB('#startDate#', INTERVAL DAYOFMONTH('#startDate#')-1 DAY) AND LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ INNER JOIN person_attribute hei_no
+ ON hei_no.person_id = p.person_id
+ AND hei_no.person_attribute_type_id = (select pat.person_attribute_type_id from person_attribute_type pat where name='HIVExposedInfant(HEI)No')
+ LEFT JOIN obs date_sample_collected
+ ON date_sample_collected.person_id = p.person_id
+ AND date_sample_collected.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'Date EID sample collected')
+ AND date_sample_collected.voided = 0
+ LEFT JOIN obs eid_age
+ ON eid_age.person_id = p.person_id
+ AND eid_age.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'EID - Age at 1st EID')
+ AND eid_age.voided = 0
+ LEFT JOIN obs outcome
+ ON outcome.person_id = p.person_id
+ AND outcome.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'Final outcome at 24 months of age')
+ AND outcome.value_coded IS NOT NULL
+ AND outcome.voided = 0
diff --git a/openmrs/apps/reports/sql/quarterly_pmtct_hei_pos.sql b/openmrs/apps/reports/sql/quarterly_pmtct_hei_pos.sql
new file mode 100644
index 000000000..55f4f44fe
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_pmtct_hei_pos.sql
@@ -0,0 +1,77 @@
+SELECT CONCAT('Reporting Month : ',CONCAT(quarter.start_mon, '-' , quarter.month)) AS 'Serial \#',
+ year_q.year AS 'Date result was delivered to the facility ',
+ NULL AS 'EID Number',
+ NULL AS 'Sex',
+ NULL AS 'Age at enrolment ' ,
+ NULL AS '0 - 2 months of age',
+ NULL AS ' 2-12 months of age',
+ NULL AS 'Date EID sample collecetd',
+ NULL AS 'Date ART initiated (DD/MM/YYY)',
+ NULL AS 'Unique ART \#',
+ NULL AS 'Reason if HIV infected infant not initiated on ART'
+FROM (
+ SELECT MONTHNAME(DATE_SUB('#startDate#', INTERVAL DAYOFMONTH('#startDate#')-1 DAY)) as start_mon,
+ MONTHNAME(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as month) quarter
+ JOIN (
+ SELECT YEAR(LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))) as year
+ )year_q
+
+UNION ALL
+
+select @a:=@a+1 as Serial, Dateresult_was_delivered_to_the_facility, EID_Number , Sex , Age_at_enrolment , 0_2_months_of_age, 2_12_months_of_age,Date_EID_sample_collecetd,
+Date_ART_initiated,Unique_ART, Reason_if_HIV_infected_infant_not_initiated_on_ART from (
+SELECT (SELECT @a:= 0),
+ DATE_FORMAT(date_delivered.value_datetime, "%d/%m/%Y") AS 'Dateresult_was_delivered_to_the_facility',
+ eid_number.value_numeric AS 'EID_Number',
+ p.gender AS 'Sex',
+ eid_age.value_numeric AS 'Age_at_enrolment' ,
+ IF(eid_age.value_numeric IS NOT NULL, IF(eid_age.value_numeric <=2, 1, ''),
+ IF(date_delivered.value_datetime IS NOT NULL AND TIMESTAMPDIFF( MONTH, p.birthdate, date_delivered.value_datetime) <=2 , 1 , '')) AS '0_2_months_of_age',
+ IF(eid_age.value_numeric IS NOT NULL, IF(eid_age.value_numeric BETWEEN 3 AND 12 , 1, ''),
+ IF(date_delivered.value_datetime IS NOT NULL AND TIMESTAMPDIFF( MONTH, p.birthdate, date_delivered.value_datetime) BETWEEN 3 AND 12 , 1 , '')) AS ' 2_12_months_of_age',
+ DATE_FORMAT(date_sample_collected.value_datetime, "%d/%m/%Y") AS 'Date_EID_sample_collecetd',
+ DATE_FORMAT(date_art_initiated.value_datetime, "%d/%m/%Y") AS 'Date_ART_initiated',
+ pid.identifier AS 'Unique_ART',
+ reason.value_text AS 'Reason_if_HIV_infected_infant_not_initiated_on_ART'
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ AND pt.voided = 0
+ INNER JOIN encounter e
+ ON e.patient_id = pt.patient_id
+ AND e.voided = 0
+ INNER JOIN obs date_delivered
+ ON date_delivered.encounter_id = e.encounter_id
+ AND date_delivered.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'EID - Date result was delivered to the facility')
+ AND date_delivered.voided = 0
+ AND date_delivered.value_datetime BETWEEN DATE_SUB('#startDate#', INTERVAL DAYOFMONTH('#startDate#')-1 DAY) AND LAST_DAY(DATE_ADD('#startDate#', INTERVAL 2 MONTH))
+ AND TIMESTAMPDIFF( MONTH, p.birthdate, date_delivered.value_datetime) <=12 -- Filter out samples collected after 12 months age
+ LEFT JOIN obs eid_number
+ ON eid_number.person_id = p.person_id
+ AND eid_number.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'EID Number')
+ AND eid_number.voided = 0
+ LEFT JOIN obs eid_age
+ ON eid_age.person_id = p.person_id
+ AND eid_age.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'EID - Age at 1st EID')
+ AND eid_age.voided = 0
+ LEFT JOIN obs date_sample_collected
+ ON date_sample_collected.person_id = p.person_id
+ AND date_sample_collected.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'Date EID sample collected')
+ AND date_sample_collected.voided = 0
+ LEFT JOIN obs date_art_initiated
+ ON date_art_initiated.person_id = p.person_id
+ AND date_art_initiated.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'HEI Treatment,Date ART initiated')
+ AND date_art_initiated.voided = 0
+ -- Primary patient identifier doubles up as ART number
+ LEFT JOIN patient_identifier pid
+ ON pid.patient_id = pt.patient_id
+ AND pid.identifier_type = (SELECT pit.patient_identifier_type_id FROM patient_identifier_type pit WHERE pit.name = 'Patient Identifier')
+ AND pid.voided = 0
+ LEFT JOIN obs reason
+ ON reason.person_id = p.person_id
+ AND reason.concept_id = (SELECT cv.concept_id FROM concept_view cv where cv.concept_full_name= 'HEI Treatment,Reason if HIV infected infant not initiated on ART')
+ AND reason.voided = 0
+ AND date_art_initiated.value_datetime IS NULL
+)p
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/quarterly_report.sql b/openmrs/apps/reports/sql/quarterly_report.sql
new file mode 100644
index 000000000..2352f474b
--- /dev/null
+++ b/openmrs/apps/reports/sql/quarterly_report.sql
@@ -0,0 +1,1187 @@
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (Index)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex in ('M','F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Index Testing')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Index Testing')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Index Testing')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Index Testing')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Index Testing')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (Emergency)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Emergency, entry point')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Emergency, entry point')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Emergency, entry point')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Emergency, entry point')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Emergency, entry point')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (Inpatient)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='In Patient')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='In Patient')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='In Patient')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='In Patient')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='In Patient')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (OPD)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Entry Point - OPD')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Entry Point - OPD')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Entry Point - OPD')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Entry Point - OPD')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Entry Point - OPD')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '1-4 yr M', 'PITC (Malnutrition facilities)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND (observed_age_group.name LIKE'<1 yr%' OR observed_age_group.name LIKE '1-4 yr%' OR observed_age_group.report_group_name='10 to 14 years')
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Malnutrition Facilities')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Malnutrition Facilities')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Malnutrition Facilities')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Malnutrition Facilities')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Malnutrition Facilities')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '1-4 yr M', 'PITC (Pediatric <5 clinic)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND (observed_age_group.report_group_name ='Less than 1 year' OR observed_age_group.report_group_name='1 to 4 years')
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Padeatric')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Padeatric')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Padeatric')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Padeatric')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Padeatric')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr F', 'PMTCT (1st ANC only)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND observed_age_group.sex = 'F'
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr F', 'PMTCT (Post ANC 1)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND observed_age_group.sex = 'F'
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='ANC Clinic')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (TB)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='TB Clinic')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='TB Clinic')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='TB Clinic')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='TB Clinic')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='TB Clinic')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'VCT','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='VCT Clinic')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='VCT Clinic')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='VCT Clinic')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='VCT Clinic')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='VCT Clinic')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
+
+
+UNION ALL
+SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
+FROM DUAL
+
+UNION ALL
+
+SELECT if(observed_age_group.name = '25-29 yr M', 'PITC (Other)','') AS 'Testing point',
+ observed_age_group.report_group_name AS 'Age Groups',
+ observed_age_group.sex AS 'SEX',
+ sum(if(tested.val is not null , 1, 0)) AS 'Total Tested',
+ sum(if(positive.val is not null , 1, 0)) AS 'Tested Positive',
+ sum(if(started.val = 1 , 1, 0)) AS 'Started ART in HF',
+ sum(if(reffered.val is not null , 1, 0)) AS 'Reffered to other site for ART',
+ sum(if(dead.val is not null , 1, 0)) AS 'Dead',
+ '' AS 'Other (Specify)'
+
+FROM
+ patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ AND p.voided = 0
+ RIGHT OUTER JOIN reporting_age_group observed_age_group
+ ON DATE(now()) BETWEEN (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.min_years YEAR), INTERVAL observed_age_group.min_days DAY))
+ AND (DATE_ADD(DATE_ADD(p.birthdate, INTERVAL observed_age_group.max_years YEAR), INTERVAL observed_age_group.max_days DAY))
+ AND CASE WHEN observed_age_group.report_group_name = 'Total All' THEN observed_age_group.sex = ('M' OR 'F') else observed_age_group.sex = p.gender END
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Plan')
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Refer')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Other Entry Point (Specify)')
+ ) AS reffered ON reffered.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Other Entry Point (Specify)')
+ ) AS positive ON positive.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_datetime AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Date First Tested HIV +')
+ AND obs.value_datetime IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Other Entry Point (Specify)')
+ ) AS tested ON tested.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='Transferred in on ART?')
+ AND obs.value_coded IS NOT NULL
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Other Entry Point (Specify)')
+ ) AS started ON started.patient_id = pt.patient_id
+ LEFT JOIN (
+ SELECT
+ pt.patient_id AS patient_id,
+ obs.value_coded AS val
+ FROM patient pt
+ INNER JOIN
+ person p ON p.person_id = pt.patient_id
+ INNER JOIN obs
+ ON obs.person_id = pt.patient_id
+ AND obs.voided=0 AND obs.concept_id IN (select concept_id from concept_view where concept_full_name ='End Of Follow Up Reason')
+ AND obs.value_coded IS NOT NULL
+ AND obs.value_coded = (select concept_id from concept_view where concept_full_name ='Death during treatment')
+ INNER JOIN obs testing_point
+ ON testing_point.person_id = pt.patient_id
+ AND testing_point.concept_id = (select concept_id from concept_view where concept_full_name ='HIV - Entry Point')
+ AND testing_point.value_coded = (select concept_id from concept_view where concept_full_name ='Other Entry Point (Specify)')
+ ) AS dead ON dead.patient_id = pt.patient_id
+ GROUP BY observed_age_group.id
diff --git a/openmrs/apps/reports/sql/summaryAppointmentReport.sql b/openmrs/apps/reports/sql/summaryAppointmentReport.sql
new file mode 100644
index 000000000..97102292c
--- /dev/null
+++ b/openmrs/apps/reports/sql/summaryAppointmentReport.sql
@@ -0,0 +1,17 @@
+SELECT DISTINCT
+ pai.identifier AS 'Patient ID',
+ pn.given_name AS 'First Name',
+ ifnull(pn.family_name,'') AS 'Last Name',
+ DATE_FORMAT(pa.start_date_time, "%d/%m/%Y") AS 'Appointment Date',
+ pa.status AS 'Status',
+ pMobile.telephoneNo AS 'Contact No.',
+ p.gender AS 'Gender'
+FROM patient_appointment pa
+ LEFT JOIN person p ON p.person_id = pa.patient_id AND pa.voided IS FALSE
+ LEFT JOIN person_name pn ON p.person_id = pn.person_id AND pn.voided IS FALSE
+ LEFT JOIN patient_identifier pai ON (pai.patient_id = pa.patient_id AND pai.preferred = 1)
+ LEFT JOIN (select paMobile.person_id as 'pMobilePersonId', paMobile.value AS 'telephoneNo' from person_attribute paMobile
+ JOIN person_attribute_type patMobile ON patMobile.name = "MobileNumber" AND patMobile.retired IS FALSE
+ AND patMobile.person_attribute_type_id = paMobile.person_attribute_type_id) AS pMobile ON pa.patient_id = pMobile.pMobilePersonId
+WHERE pa.appointment_kind = 'Scheduled' AND pa.start_date_time BETWEEN '#startDate#' AND '#endDate#'
+ORDER BY pa.start_date_time DESC;
diff --git a/openmrs/apps/reports/sql/tbARTdatacollectiontool.sql b/openmrs/apps/reports/sql/tbARTdatacollectiontool.sql
new file mode 100644
index 000000000..5d3978cf3
--- /dev/null
+++ b/openmrs/apps/reports/sql/tbARTdatacollectiontool.sql
@@ -0,0 +1,60 @@
+select @a:=@a+1 Serial, date_tB_treatment_initiated as 'Date TB treatment initiated' , Age , sex , IFNULL(tHivStatus.hivstatus,'N/A') as 'HIV Status' , IFNULL(client_on_arts,'N/A') as 'Client On ART?' , artnumber as 'Unique ART Number' from (
+select * from (
+select (SELECT @a:= 0) AS a , person_id, concept_id, obs_datetime as 'On TB Treatment' , encounter_id , value_coded , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnTBTreatment
+left join
+(
+select pa.person_id, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex ,floor(datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo')
+)tdemographics
+on tOnTBTreatment.person_id = tdemographics.person_id
+left join (
+select * from (
+select person_id, concept_id, obs_datetime as 'date_tB_treatment_initiated' , encounter_id , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Started TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id = (select concept_id from concept_name where name = 'Date Started TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tDateStartedTBtreatment on tOnTBTreatment.person_id = tDateStartedTBtreatment.person_id
+left join
+(
+select pid , tConceptname.name as 'hivstatus' from (
+select distinct(person_id) as pid, obs_datetime , value_coded
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded, voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and voided = 0
+)a inner join
+(select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening - HIV Status' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime
+ between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCodedAnswers
+left join
+(
+select concept_id , name from concept_name where concept_name_type = 'FULLY_SPECIFIED' and voided = 0
+)tConceptname on tCodedAnswers.value_coded = tConceptname.concept_id
+)tHivStatus on tOnTBTreatment.person_id = tHivStatus.pid
+left join
+(
+select person_id ,
+(case when value_coded = 1 then 'Yes' else 'No' end) as 'client_on_arts'
+ from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded , voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(LAST_DAY('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnArtTreatment on tOnTBTreatment.person_id = tOnArtTreatment.person_id
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_newly_started.sql b/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_newly_started.sql
new file mode 100644
index 000000000..4c6c0eb2c
--- /dev/null
+++ b/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_newly_started.sql
@@ -0,0 +1,267 @@
+select 'less than 15 Years' as 'Age Group' ,sex,
+count(distinct(case when pid is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Newly started on ART',
+count(distinct(case when tbscreeningCurrentCough is not null or tbscreeningfever is not null or tbscreeningweightloss is not null or tbscreeningNightsweats is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Screened for TB symptoms',
+count(distinct(case when tbscreeningCurrentCough = 1 and tbscreeningfever = 1 and tbscreeningweightloss = 1 and tbscreeningNightsweats = 1 and age < 15 and sex in ('F', 'M') then pid end)) as 'TB Suspect/Presumptive TB',
+count(distinct(case when afbMicroscropicdateresultreceived is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Specimen Sent to Lab - AFB Microscopy',
+count(distinct(case when geneXpertdateresultreceived is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Specimen Sent to Lab - GeneXpert',
+count(distinct(case when crxdateresultreceived is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Specimen Sent to Lab - Other: X-Ray',
+count(distinct(case when istbdiagnosed is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'TB Case',
+count(distinct(case when onTBTreatment is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Treated for TB',
+count(distinct(case when scheduledipt is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'No. of ART patients who are scheduled to complete 6 months of IPT/TPT',
+count(distinct(case when iptCompleted is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'No. of ART patients who completed 6 months of IPT/TPT'
+from (
+select person_id, arvreceivedbefore from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'arvreceivedbefore', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvsReceivedBefore
+inner join(
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M')
+)tDemographics on tArvsReceivedBefore.person_id = tDemographics.pid
+left join (
+select person_id, tbscreeningCurrentCough from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningCurrentCough', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1, 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBscreeningCurrentCough on tArvsReceivedBefore.person_id = tTBscreeningCurrentCough.person_id
+left join(
+select person_id, tbscreeningfever from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningfever', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1,2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbScreeningfever on tArvsReceivedBefore.person_id = tTbScreeningfever.person_id
+left join(
+select person_id, tbscreeningweightloss from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningweightloss', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningWeightloss on tArvsReceivedBefore.person_id = tTBScreeningWeightloss.person_id
+left join(
+select person_id, tbscreeningNightsweats from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningNightsweats', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningNightSweats on tArvsReceivedBefore.person_id = tTBScreeningNightSweats.person_id
+left join (
+select person_id, afbMicroscropicdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'afbMicroscropicdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAfbDateresultsreceivedinlab on tArvsReceivedBefore.person_id = tAfbDateresultsreceivedinlab.person_id
+left join (
+select person_id, geneXpertdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'geneXpertdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tGenexpertdatereceivedinlab on tArvsReceivedBefore.person_id = tGenexpertdatereceivedinlab.person_id
+left join(
+select person_id, crxdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'crxdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCrxdateresultreceived on tArvsReceivedBefore.person_id = tCrxdateresultreceived.person_id
+left join (
+select person_id, istbdiagnosed from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'istbdiagnosed', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsTBDiagnosed on tArvsReceivedBefore.person_id = tIsTBDiagnosed.person_id
+left join (
+select person_id, onTBTreatment from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'onTBTreatment', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnTBTreatment on tArvsReceivedBefore.person_id = tOnTBTreatment.person_id
+left join(
+select person_id, scheduledipt from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'scheduledipt', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tscheduledIPT on tArvsReceivedBefore.person_id = tscheduledIPT.person_id
+left join(
+select person_id, iptCompleted from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'iptCompleted', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'IPT - Completed' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIptCompleted on tArvsReceivedBefore.person_id = tIptCompleted.person_id group by sex
+union all
+select '15 Years And Above' as 'Age Group' ,sex,
+count(distinct(case when pid is not null and age >= 15 then pid end)) as 'Newly started on ART',
+count(distinct(case when tbscreeningCurrentCough is not null or tbscreeningfever is not null or tbscreeningweightloss is not null or tbscreeningNightsweats is not null and age >= 15 then pid end)) as 'Screened for TB symptoms',
+count(distinct(case when tbscreeningCurrentCough = 1 and tbscreeningfever = 1 and tbscreeningweightloss = 1 and tbscreeningNightsweats = 1 and age >= 15 then pid end)) as 'TB Suspect/Presumptive TB',
+count(distinct(case when afbMicroscropicdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - AFB Microscopy',
+count(distinct(case when geneXpertdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - GeneXpert',
+count(distinct(case when crxdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - Other: X-Ray',
+count(distinct(case when istbdiagnosed is not null and age >= 15 and sex in ('F', 'M') then pid end)) as 'TB Case',
+count(distinct(case when onTBTreatment is not null and age >= 15 and sex in ('F', 'M') then pid end)) as 'Treated for TB',
+count(distinct(case when scheduledipt is not null and age >= 15 then pid end)) as 'No. of ART patients who are scheduled to complete 6 months of IPT/TPT',
+count(distinct(case when iptCompleted is not null and age >= 15 then pid end)) as 'No. of ART patients who completed 6 months of IPT/TPT'
+from (
+select person_id, arvreceivedbefore from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'arvreceivedbefore', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvsReceivedBefore
+inner join(
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M')
+)tDemographics on tArvsReceivedBefore.person_id = tDemographics.pid
+left join (
+select person_id, tbscreeningCurrentCough from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningCurrentCough', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1, 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBscreeningCurrentCough on tArvsReceivedBefore.person_id = tTBscreeningCurrentCough.person_id
+left join(
+select person_id, tbscreeningfever from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningfever', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1,2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbScreeningfever on tArvsReceivedBefore.person_id = tTbScreeningfever.person_id
+left join(
+select person_id, tbscreeningweightloss from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningweightloss', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningWeightloss on tArvsReceivedBefore.person_id = tTBScreeningWeightloss.person_id
+left join(
+select person_id, tbscreeningNightsweats from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningNightsweats', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningNightSweats on tArvsReceivedBefore.person_id = tTBScreeningNightSweats.person_id
+left join (
+select person_id, afbMicroscropicdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'afbMicroscropicdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAfbDateresultsreceivedinlab on tArvsReceivedBefore.person_id = tAfbDateresultsreceivedinlab.person_id
+left join (
+select person_id, geneXpertdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'geneXpertdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tGenexpertdatereceivedinlab on tArvsReceivedBefore.person_id = tGenexpertdatereceivedinlab.person_id
+left join(
+select person_id, crxdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'crxdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCrxdateresultreceived on tArvsReceivedBefore.person_id = tCrxdateresultreceived.person_id
+left join (
+select person_id, istbdiagnosed from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'istbdiagnosed', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsTBDiagnosed on tArvsReceivedBefore.person_id = tIsTBDiagnosed.person_id
+left join (
+select person_id, onTBTreatment from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'onTBTreatment', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnTBTreatment on tArvsReceivedBefore.person_id = tOnTBTreatment.person_id
+left join(
+select person_id, scheduledipt from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'scheduledipt', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tscheduledIPT on tArvsReceivedBefore.person_id = tscheduledIPT.person_id
+left join(
+select person_id, iptCompleted from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'iptCompleted', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'IPT - Completed' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIptCompleted on tArvsReceivedBefore.person_id = tIptCompleted.person_id group by sex
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_previously_started_on_art.sql b/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_previously_started_on_art.sql
new file mode 100644
index 000000000..804a08851
--- /dev/null
+++ b/openmrs/apps/reports/sql/tx_tb_ and_tb_prev_previously_started_on_art.sql
@@ -0,0 +1,267 @@
+select 'less than 15 Years' as 'Age Group' ,sex,
+count(distinct(case when pid is not null and age < 15 then pid end)) as 'Newly started on ART',
+count(distinct(case when tbscreeningCurrentCough is not null or tbscreeningfever is not null or tbscreeningweightloss is not null or tbscreeningNightsweats is not null and age < 15 then pid end)) as 'Screened for TB symptoms',
+count(distinct(case when tbscreeningCurrentCough = 1 and tbscreeningfever = 1 and tbscreeningweightloss = 1 and tbscreeningNightsweats = 1 and age < 15 then pid end)) as 'TB Suspect/Presumptive TB',
+count(distinct(case when afbMicroscropicdateresultreceived is not null and age < 15 then pid end)) as 'Specimen Sent to Lab - AFB Microscopy',
+count(distinct(case when geneXpertdateresultreceived is not null and age < 15 then pid end)) as 'Specimen Sent to Lab - GeneXpert',
+count(distinct(case when crxdateresultreceived is not null and age < 15 then pid end)) as 'Specimen Sent to Lab - Other: X-Ray',
+count(distinct(case when istbdiagnosed is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'TB Case',
+count(distinct(case when onTBTreatment is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Treated for TB',
+count(distinct(case when scheduledipt is not null and age < 15 then pid end)) as 'No. of ART patients who are scheduled to complete 6 months of IPT/TPT',
+count(distinct(case when iptCompleted is not null and age < 15 then pid end)) as 'No. of ART patients who completed 6 months of IPT/TPT'
+from (
+select person_id, arvreceivedbefore from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'arvreceivedbefore', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 2 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvsReceivedBefore
+inner join(
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M')
+)tDemographics on tArvsReceivedBefore.person_id = tDemographics.pid
+left join (
+select person_id, tbscreeningCurrentCough from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningCurrentCough', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1, 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBscreeningCurrentCough on tArvsReceivedBefore.person_id = tTBscreeningCurrentCough.person_id
+left join(
+select person_id, tbscreeningfever from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningfever', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1,2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbScreeningfever on tArvsReceivedBefore.person_id = tTbScreeningfever.person_id
+left join(
+select person_id, tbscreeningweightloss from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningweightloss', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningWeightloss on tArvsReceivedBefore.person_id = tTBScreeningWeightloss.person_id
+left join(
+select person_id, tbscreeningNightsweats from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningNightsweats', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningNightSweats on tArvsReceivedBefore.person_id = tTBScreeningNightSweats.person_id
+left join (
+select person_id, afbMicroscropicdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'afbMicroscropicdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAfbDateresultsreceivedinlab on tArvsReceivedBefore.person_id = tAfbDateresultsreceivedinlab.person_id
+left join (
+select person_id, geneXpertdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'geneXpertdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tGenexpertdatereceivedinlab on tArvsReceivedBefore.person_id = tGenexpertdatereceivedinlab.person_id
+left join(
+select person_id, crxdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'crxdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCrxdateresultreceived on tArvsReceivedBefore.person_id = tCrxdateresultreceived.person_id
+left join (
+select person_id, istbdiagnosed from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'istbdiagnosed', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsTBDiagnosed on tArvsReceivedBefore.person_id = tIsTBDiagnosed.person_id
+left join (
+select person_id, onTBTreatment from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'onTBTreatment', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnTBTreatment on tArvsReceivedBefore.person_id = tOnTBTreatment.person_id
+left join(
+select person_id, scheduledipt from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'scheduledipt', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tscheduledIPT on tArvsReceivedBefore.person_id = tscheduledIPT.person_id
+left join(
+select person_id, iptCompleted from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'iptCompleted', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'IPT - Completed' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIptCompleted on tArvsReceivedBefore.person_id = tIptCompleted.person_id group by sex
+union all
+select '15 Years And Above' as 'Age Group' ,sex,
+count(distinct(case when pid is not null and age >= 15 then pid end)) as 'Newly started on ART',
+count(distinct(case when tbscreeningCurrentCough is not null or tbscreeningfever is not null or tbscreeningweightloss is not null or tbscreeningNightsweats is not null and age >= 15 then pid end)) as 'Screened for TB symptoms',
+count(distinct(case when tbscreeningCurrentCough = 1 and tbscreeningfever = 1 and tbscreeningweightloss = 1 and tbscreeningNightsweats = 1 and age >= 15 then pid end)) as 'TB Suspect/Presumptive TB',
+count(distinct(case when afbMicroscropicdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - AFB Microscopy',
+count(distinct(case when geneXpertdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - GeneXpert',
+count(distinct(case when crxdateresultreceived is not null and age >= 15 then pid end)) as 'Specimen Sent to Lab - Other: X-Ray',
+count(distinct(case when istbdiagnosed is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'TB Case',
+count(distinct(case when onTBTreatment is not null and age < 15 and sex in ('F', 'M') then pid end)) as 'Treated for TB',
+count(distinct(case when scheduledipt is not null and age >= 15 then pid end)) as 'No. of ART patients who are scheduled to complete 6 months of IPT/TPT',
+count(distinct(case when iptCompleted is not null and age >= 15 then pid end)) as 'No. of ART patients who completed 6 months of IPT/TPT'
+from (
+select person_id, arvreceivedbefore from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'arvreceivedbefore', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 2 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Were ARVS Received?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tArvsReceivedBefore
+inner join(
+select pa.person_id as pid, pa.value as 'artnumber' , concat(coalesce(given_name, ''), " ", coalesce(middle_name, ''), ' ', coalesce(family_name , '') ) as 'ClientName',
+gender as sex , (datediff(curdate(),p.birthdate) / 365) as 'Age'
+from person_attribute as pa
+INNER JOIN person_attribute_type as pat on pa.person_attribute_type_id = pat.person_attribute_type_id
+INNER JOIN person as p on pa.person_id = p.person_id
+LEFT JOIN person_name as pn on p.person_id = pn.person_id
+LEFT JOIN patient as pt on p.person_id = pt.patient_id
+where pa.person_attribute_type_id = (select person_attribute_type_id from person_attribute_type where name = 'UniqueArtNo') and gender in ('F', 'M')
+)tDemographics on tArvsReceivedBefore.person_id = tDemographics.pid
+left join (
+select person_id, tbscreeningCurrentCough from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningCurrentCough', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1, 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Current Cough' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBscreeningCurrentCough on tArvsReceivedBefore.person_id = tTBscreeningCurrentCough.person_id
+left join(
+select person_id, tbscreeningfever from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningfever', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1,2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Fever' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTbScreeningfever on tArvsReceivedBefore.person_id = tTbScreeningfever.person_id
+left join(
+select person_id, tbscreeningweightloss from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningweightloss', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening ,Weight loss' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningWeightloss on tArvsReceivedBefore.person_id = tTBScreeningWeightloss.person_id
+left join(
+select person_id, tbscreeningNightsweats from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'tbscreeningNightsweats', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded in (1 , 2) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Screening , Night Sweats' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tTBScreeningNightSweats on tArvsReceivedBefore.person_id = tTBScreeningNightSweats.person_id
+left join (
+select person_id, afbMicroscropicdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'afbMicroscropicdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Microscopic' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tAfbDateresultsreceivedinlab on tArvsReceivedBefore.person_id = tAfbDateresultsreceivedinlab.person_id
+left join (
+select person_id, geneXpertdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'geneXpertdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, GeneXpert' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tGenexpertdatereceivedinlab on tArvsReceivedBefore.person_id = tGenexpertdatereceivedinlab.person_id
+left join(
+select person_id, crxdateresultreceived from (
+select person_id, concept_id, obs_datetime , encounter_id , value_datetime as 'crxdateresultreceived', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59')
+ and voided = 0 )a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'Date Results Received, Crx' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+ and obs_datetime > '#startDate#' and obs_datetime <= DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tCrxdateresultreceived on tArvsReceivedBefore.person_id = tCrxdateresultreceived.person_id
+left join (
+select person_id, istbdiagnosed from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'istbdiagnosed', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'TB Diagnosed?' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIsTBDiagnosed on tArvsReceivedBefore.person_id = tIsTBDiagnosed.person_id
+left join (
+select person_id, onTBTreatment from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'onTBTreatment', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'On TB Treatment' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tOnTBTreatment on tArvsReceivedBefore.person_id = tOnTBTreatment.person_id
+left join(
+select person_id, scheduledipt from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'scheduledipt', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded = 1 and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Schedule(6months)' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tscheduledIPT on tArvsReceivedBefore.person_id = tscheduledIPT.person_id
+left join(
+select person_id, iptCompleted from (
+select person_id, concept_id, obs_datetime , encounter_id , value_coded as 'iptCompleted', voided from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0)
+and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') and value_coded =
+(select concept_id from concept_name where name = 'IPT - Completed' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and voided = 0
+)a inner join (select person_id as pid , concept_id as cid, max(encounter_id) maxdate from obs where concept_id =
+(select concept_id from concept_name where name = 'IPT Status - TB Screening' and concept_name_type = 'FULLY_SPECIFIED' and voided = 0) and obs_datetime between DATE_FORMAT('#startDate#','%Y-%m-01') and DATE_FORMAT(('#endDate#'),'%Y-%m-%d 23:59:59') group by pid) c on
+a.person_id = c.pid and a.encounter_id = c.maxdate
+)tIptCompleted on tArvsReceivedBefore.person_id = tIptCompleted.person_id group by sex
\ No newline at end of file
diff --git a/openmrs/apps/reports/sql/visitAppointmentReport.sql b/openmrs/apps/reports/sql/visitAppointmentReport.sql
new file mode 100644
index 000000000..182dab1ae
--- /dev/null
+++ b/openmrs/apps/reports/sql/visitAppointmentReport.sql
@@ -0,0 +1,22 @@
+SELECT DISTINCT
+ pai.identifier AS 'Patient ID',
+ pn.given_name AS 'First Name',
+ ifnull(pn.family_name,'') AS 'Last Name',
+ DATE_FORMAT(pa.start_date_time, "%d/%m/%Y") AS 'Visit Date',
+ pa.appointment_kind AS 'Visit Type',
+ pMobile.telephoneNo AS 'Contact No.',
+ p.gender AS 'Gender'
+FROM patient_appointment pa
+ LEFT JOIN person p ON p.person_id = pa.patient_id AND pa.voided IS FALSE
+ LEFT JOIN person_name pn ON p.person_id = pn.person_id AND pn.voided IS FALSE
+ LEFT JOIN patient_identifier pai ON (pai.patient_id = pa.patient_id AND pai.preferred = 1)
+ LEFT JOIN (select paMobile.person_id as 'pMobilePersonId', paMobile.value AS 'telephoneNo' from person_attribute paMobile
+ JOIN person_attribute_type patMobile ON patMobile.name = "MobileNumber" AND patMobile.retired IS FALSE
+ AND patMobile.person_attribute_type_id = paMobile.person_attribute_type_id) AS pMobile ON pa.patient_id = pMobile.pMobilePersonId
+ LEFT JOIN (SELECT v.patient_id AS 'visitPatientId',
+ v.visit_id AS visitId, v.date_started AS visitStartDate, vt.name AS visitType FROM visit v
+ JOIN visit_type vt ON (v.visit_type_id = vt.visit_type_id and vt.retired IS FALSE)
+ HAVING v.visit_id = (SELECT MAX(maxV.visit_id) AS maxVisitId
+ FROM visit maxV WHERE maxV.patient_id = v.patient_id)) AS patientVisit ON patientVisit.visitPatientId = pa.patient_id
+WHERE pa.start_date_time BETWEEN '#startDate#' AND '#endDate#'
+ORDER BY pa.start_date_time DESC;
diff --git a/openmrs/apps/reports/sql/walkinAppointmentReport.sql b/openmrs/apps/reports/sql/walkinAppointmentReport.sql
new file mode 100644
index 000000000..42b30d80b
--- /dev/null
+++ b/openmrs/apps/reports/sql/walkinAppointmentReport.sql
@@ -0,0 +1,17 @@
+SELECT DISTINCT
+ pai.identifier AS 'patient ID',
+ pn.given_name AS 'First Name',
+ ifnull(pn.family_name,'') AS 'Last Name',
+ DATE_FORMAT(pa.start_date_time, "%d/%m/%Y") AS 'Visit Date',
+ pa.appointment_kind AS 'Visit Type',
+ pMobile.telephoneNo AS 'Contact No.',
+ p.gender AS 'Gender'
+FROM patient_appointment pa
+ LEFT JOIN person p ON p.person_id = pa.patient_id AND pa.voided IS FALSE
+ LEFT JOIN person_name pn ON p.person_id = pn.person_id AND pn.voided IS FALSE
+ LEFT JOIN patient_identifier pai ON (pai.patient_id = pa.patient_id AND pai.preferred = 1)
+ LEFT JOIN (select paMobile.person_id as 'pMobilePersonId', paMobile.value AS 'telephoneNo' from person_attribute paMobile
+ JOIN person_attribute_type patMobile ON patMobile.name = "MobileNumber" AND patMobile.retired IS FALSE
+ AND patMobile.person_attribute_type_id = paMobile.person_attribute_type_id) AS pMobile ON pa.patient_id = pMobile.pMobilePersonId
+WHERE pa.appointment_kind = 'WalkIn' AND pa.start_date_time BETWEEN '#startDate#' AND '#endDate#'
+ORDER BY pa.start_date_time DESC;
diff --git a/openmrs/i18n/clinical/locale_en.json b/openmrs/i18n/clinical/locale_en.json
index aeae74e36..cf3f6ffd8 100644
--- a/openmrs/i18n/clinical/locale_en.json
+++ b/openmrs/i18n/clinical/locale_en.json
@@ -1,9 +1,13 @@
{
"MODULE_LABEL_ACTIVE_KEY": "Active",
- "MODULE_LABEL_PROGRAMS_KEY": "Programs",
+ "MODULE_LABEL_HEI_KEY": "HEI",
"MODULE_LABEL_MY_PATIENTS_KEY": "My Patients",
+ "MODULE_LABEL_HEI_TO_ART_PATIENTS": "HEI TO ART PATIENTS",
"MODULE_LABEL_ACTIVE_PATIENTS_BY_LOCATION": "PatientsByLocation",
- "MODULE_LABEL_OPD_1_KEY": "OPD-1",
+ "MODULE_LABEL_OPD_1_KEY": "CONSULTATION",
+ "MODULE_LABEL_PMTCT_KEY": "PMTCT",
+ "MODULE_LABEL_DRUGS_PATIENTS_KEY": "PATIENTS DRUG QUEUE",
+ "MODULE_LABEL_VIRAL_LOAD_PATIENTS_KEY": "VIRAL LOAD",
"MODULE_LABEL_ALL_KEY": "All",
"DASHBOARD_TITLE_LAB_RESULTS_KEY": "Lab Results",
@@ -13,11 +17,16 @@
"DASHBOARD_TITLE_VISITS_KEY": "Visits",
"DASHBOARD_TITLE_PROGRAMS_KEY": "Programs",
"DASHBOARD_TITLE_TREATMENTS_KEY": "Treatments",
- "DASHBOARD_TITLE_DISPOSITION_KEY": "Disposition",
+ "DASHBOARD_TITLE_DISPOSITION_KEY": "Referral",
"DASHBOARD_TITLE_DIAGNOSIS_KEY": "Diagnosis",
"DASHBOARD_TITLE_ADMISSION_DETAILS_KEY": "Admission Details",
"DASHBOARD_TITLE_NUTRITIONAL_VALUES_KEY": "Nutritional Values",
- "DASHBOARD_TITLE_SECOND_VITALS_KEY": "Second Vitals",
+ "DASHBOARD_TITLE_VIRAL_LOAD_AND_EAC_RESULTS_KEY": "Viral load And EAC Dates",
+ "DASHBOARD_TITLE_CD4_KEY": "CD4 Details",
+ "DASHBOARD_TITLE_CONTACTS_INFO" : "Sexual Contacts Information",
+ "DASHBOARD_TITLE_TB_DIAGNOSIS": "TB DIAGNOSIS STATUS",
+ "DASHBOARD_TITLE_TB_IPT_STATUS": "IPT_STATUS",
+ "DASHBOARD_TITLE_SECOND_VITALS_KEY": "Second Vitals",
"DASHBOARD_TITLE_GYNAECOLOGY_KEY": "Gynaecology",
"DASHBOARD_TITLE_HISTORY_AND_EXAMINATIONS_KEY": "History and Examinations",
"DASHBOARD_TITLE_OBSTETRICS_KEY": "Obstetrics",
@@ -53,11 +62,11 @@
"OBSERVATIONS_BOARD_LABEL_KEY":"Observations",
- "MEDICATIONS_BOARD_LABEL_KEY":"Medications",
+ "MEDICATIONS_BOARD_LABEL_KEY":"ARV Regimen / Medications",
"ORDERS_BOARD_LABEL_KEY":"Orders",
"BACTERIOLOGY_BOARD_LABEL_KEY":"Bacteriology",
"CONSULTATION_BOARD_LABEL_KEY":"Consultation",
- "DISPOSITION_BOARD_LABEL_KEY":"Disposition",
+ "DISPOSITION_BOARD_LABEL_KEY":"Referral",
"DIAGNOSIS_BOARD_LABEL_KEY":"Diagnosis",
"CLINICAL_ORDER_RADIOLOGY_NEED_PRINT": "Need Print for this order.",
@@ -74,15 +83,20 @@
"DASHBOARD_TITLE_Consultation_KEY": "Consultation Notes",
"DASHBOARD_TITLE_APPOINTMENTS_KEY": "Appointments",
+ "DASHBOARD_TITLE_PATIENT_CONTACTS_KEY": "Patient Contacts",
"DASHBOARD_APPOINTMENTS_SLOT_KEY": "Slot",
"DASHBOARD_APPOINTMENTS_SERVICE_KEY": "Service",
- "DASHBOARD_APPOINTMENTS_SERVICE_TYPE_KEY": "Service Appointment Type",
+ "DASHBOARD_APPOINTMENTS_SERVICE_TYPE_KEY": "Location",
"DASHBOARD_APPOINTMENTS_DATE_KEY": "Date",
"DASHBOARD_APPOINTMENTS_PROVIDER_KEY": "Provider",
"DASHBOARD_APPOINTMENTS_STATUS_KEY": "Status",
"DASHBOARD_PAST_APPOINTMENTS_KEY": "Past Appointments",
"DASHBOARD_UPCOMING_APPOINTMENTS_KEY": "Upcoming Appointments",
"DASHBOARD_UPCOMING_APPOINTMENTS_KEY_LINK": "List View",
+ "DASHBOARD_PATIENT_CONTACTS_KEY": "Patient's Contacts",
+ "DASHBOARD_NO_PATIENT_CONTACTS_KEY": "No Patient's Contacts",
"DASHBOARD_NO_PAST_APPOINTMENTS_KEY": "No past appointments",
+ "DASHBOARD_NO_ELICITED_CONTACTS_KEY": "No Patient's Contacts Information",
+ "DASHBOARD_ELICITED_CONTACTS_INFORMATION_KEY": "Patient Contacts Information",
"DASHBOARD_NO_UPCOMING_APPOINTMENTS_KEY": "No upcoming appointments"
}
diff --git a/openmrs/i18n/registration/locale_en.json b/openmrs/i18n/registration/locale_en.json
index f3141e655..6cd53393d 100644
--- a/openmrs/i18n/registration/locale_en.json
+++ b/openmrs/i18n/registration/locale_en.json
@@ -21,5 +21,6 @@
"REGISTRATION_INSTITUTE_ADDRESS": "Ganiyari, District - Bilaspur",
"FEE_INFORMATION_LOCALE_KEY": "Fee Information",
"NUTRITIONAL_VALUES_LOCALE_KEY": "Nutritional Values",
- "REGISTRATION_PRINT_WITH_BARCODE": "Barcode Print"
+ "REGISTRATION_PRINT_WITH_BARCODE": "Barcode Print",
+ "TREATMENT_SUPPORTER_LOCALE_KEY": "Treatment Supporter"
}
\ No newline at end of file
diff --git a/openmrs/migrations/bedManagement/PatientWardDetails.sql b/openmrs/migrations/bedManagement/PatientWardDetails.sql
deleted file mode 100644
index 9c0b463b1..000000000
--- a/openmrs/migrations/bedManagement/PatientWardDetails.sql
+++ /dev/null
@@ -1,29 +0,0 @@
-DELETE FROM global_property WHERE property = 'emrapi.sqlGet.allWardsListDetails';
-SELECT uuid() INTO @uuid;
-INSERT INTO global_property (`property`, `property_value`, `description`, `uuid`)
-VALUES ('emrapi.sqlGet.allWardsListDetails',
-"SELECT
- bed_tags.bed_tags AS 'Bed Tags',
- bed.bed_number AS 'Bed Number',
- patient_identifier.identifier AS 'Patient ID',
- CONCAT(pn.given_name, ' ', pn.family_name) AS 'Patient Name',
- TIMESTAMPDIFF(YEAR, p.birthdate, CURDATE()) AS 'Age'
-FROM
- bed
- INNER JOIN bed_location_map blm ON blm.bed_id = bed.bed_id
- INNER JOIN location l ON l.location_id = blm.location_id AND l.name = ${location_name} AND l.name LIKE '%Ward%' AND l.retired IS FALSE
- LEFT OUTER JOIN bed_patient_assignment_map bpam ON bpam.bed_id = bed.bed_id AND bpam.date_stopped IS NULL
- LEFT OUTER JOIN person p ON p.person_id = bpam.patient_id AND p.voided IS FALSE
- LEFT OUTER JOIN person_name pn ON pn.person_id = p.person_id AND pn.voided IS FALSE
- LEFT OUTER JOIN patient_identifier ON patient_identifier.patient_id = p.person_id AND patient_identifier.voided IS FALSE
- LEFT OUTER JOIN person_address address ON address.person_id = p.person_id AND address.voided IS FALSE
- LEFT OUTER JOIN (
- SELECT
- bed_tag_map.bed_id AS 'bed_id',
- GROUP_CONCAT(DISTINCT bed_tag.name ORDER BY bed_tag.name) AS 'bed_tags'
- FROM
- bed_tag_map
- INNER JOIN bed_tag ON bed_tag.bed_tag_id = bed_tag_map.bed_tag_id AND bed_tag_map.voided IS FALSE
- GROUP BY bed_tag_map.bed_id
- ) bed_tags ON bed_tags.bed_id = bed.bed_id
-GROUP BY bed.bed_number;",'SQL query to get list of bed details in ward',@uuid);
diff --git a/openmrs/migrations/liquibase.xml b/openmrs/migrations/liquibase.xml
index a70d1c277..064dc3d4f 100644
--- a/openmrs/migrations/liquibase.xml
+++ b/openmrs/migrations/liquibase.xml
@@ -49,10 +49,6 @@
);
-
- Updating SQL query for Bed Management List View
-
-