Chartjs-How to calculate the number of columns in a database with specific values (Query)

1👍

Your problem is that you are COUNTing a boolean expression: a.status=1 which will always count 1 (unless a.status is null), regardless of whether the expression is true or false. Instead of COUNTing those values, SUM them instead:

$sql = "SELECT b.year_name as year, SUM(a.status=1) as total 
        from tbl_student as a 
        left join tbl_year as b on b.id_year=a.year
        GROUP BY a.tbl_year 
        ORDER BY year ASC" ;

0👍

If your student table just has 1&0 status, the sum value of the status column is just your desired result which is the number of active students every year.like below:

select
    a.year_name,
    sum(b.status) as active_student_count
from
    tbl_year a
left join
    tbl_student b on a.id_year = b.year
group by
    a.year_name

And if your student status is not just only two values, and also has other status such as 2,3,4…and only 1 represent the active status, you can use the “case when” expresions in your SQL, like below:

select
    a.year_name,
    sum(case when b.status=1 then 1 else 0 end) as active_student_count
from
    tbl_year a
left join
    tbl_student b on a.id_year = b.year
group by
    a.year_name

Just hope it would work for you.

0👍

In the controller add this code:

$activeStudents = $this->student_model->count_student_active(array('status'=>1);

Add this code in student_model:

public function count_student_active($where)
   {

       $this->db->select();

       $this->db->from('tbl_student');

       $query = $this->db->get_where('', $where);

       $result = $query->num_rows();

       return $result;

   }

0👍

$sql = "SELECT count(*),year.year_name FROM `student` INNER JOIN year on student.year = year.id where student.status = '1' GROUP BY student.year" ;
return $this->db->query($sql)->result();

Leave a comment