Calculate age based on two dates and group_by age range using Codeigniter

Viewed 47

I'm working on a project using Codeigniter and I'm facing a problem I would like that someone can help I want display data using quey builder. so i would like to calculate the age of patients based on two dates, date of birth and registration date, I would like to know the age of the patient at the time of his treatment so for this i have a TABLE named THE_PATIENT which contains id, patient_name, date_of_birth, abou_patient, created_at. So i would like to display the total of patients recorded in the THE_PATIENT Table, calculate age of patients from date_of_birth to created_at, and add cases if age between 1y to 15y range = kid , else if age between 16y to 70y range = adult , else if age over 70 range = old_adult , after geting data i want to group_by age range and display it in my view. Any help will be appreciated Thank you for your assistance.

Best regards

class My_model extends CI_Model {
       
 function get_patients_age_range() {
  $q = $this->db->select(' the_patient.patient_name, COUNT(the_patient.patient_name) as total_patiens,
 DATEDIFF (YEAR, the_patient.date_of_birth , the_patient.created_at) AS AGE,
 SUM(AGE < 15) AS numKids,
 SUM(AGE >= 15 AND AGE < 69) AS numAdults,
 SUM(AGE >= 69) AS olderAdults, ')
                              ->from('the_patien')
                              ->group_by('patient_age_ranges')
                              ->get();
                  return $q->result();
              }
        }
1 Answers

You can use SELECT SUM() from this.

A simplified example (just add your date calculations in) is

SELECT COUNT(*) AS totalPatients, SUM(age <= 15) AS numKids, SUM(age > 15) AS numAdults

Then add your grouping and any where conditions etc.

SELECT ageGgoup, COUNT(*) AS totalPatients, SUM(age <= 15) AS numKids, SUM(age > 15 AND age <= 69) AS numAdults, SUM(age > 69) AS olderAdults GROUP BY ageGroup
Related