I am having a problem producing a result with my query. I wanted to produce SUM of the result of rows from another table which is related to the primary table.
What I failed to output is the sum of payments, and the sum of payables.
PROBLEM #1 - I cannot produce a correct output of the Payments. The query seemed to produce an formula of
numrows * sum_of_payments
PROBLEM #2 - I cannot produce an output of the total payables.
I am using Codeigniter 3 and this is my model.
function fetch_billing_records($case_id, $patient_id, $status) {
$this->db->join('cases', 'cases.id = billing.case_id', 'left');
$this->db->join('patients', 'patients.id = cases.patient_id', 'left');
$this->db->join('users', 'users.username = billing.user', 'left');
$this->db->join('billing_payments', 'billing_payments.billing_id = billing.id', 'left');
$this->db->join('billing_items', 'billing_items.billing_id = billing.id', 'left');
$this->db->join('services', 'services.title = billing_items.service', 'left');
$this->db->select('
billing.id,
billing.remarks,
billing.status,
billing.created_at,
billing.updated_at,
users.name as user,
users.username,
cases.id as case_id,
cases.title as case_title,
patients.id as patient_id,
CONCAT(patients.lastname, ", ", patients.fullname) as patient_name,
SUM(billing_payments.amount) as payments,
SUM((services.amount - billing_items.discount)*billing_items.qty) as payables
');
if(is_int($case_id)) {
$this->db->where('billing.case_id', $case_id);
}
if(is_int($patient_id)) {
$this->db->where('patients.id', $patient_id);
}
if(is_int($status)) {
$this->db->where('billing.status', $status);
}
$this->db->group_by('billing.id');
$this->db->where('billing.is_deleted', 0);
$query = $this->db->get("billing");
log_message('error', $this->db->last_query());
if ($query->num_rows() > 0) {
return $query->result_array();
}
return false;
}
I saved the Last Query with the Last Query and Log Helpers, and it seemed that the query for my instance is
SELECT `billing`.`id`, `billing`.`remarks`, `billing`.`status`, `billing`.`created_at`, `billing`.`updated_at`, `users`.`name` as `user`, `users`.`username`, `cases`.`id` as `case_id`, `cases`.`title` as `case_title`, `patients`.`id` as `patient_id`, CONCAT(patients.lastname, ", ", patients.fullname) as patient_name, SUM(billing_payments.amount) as payments, SUM((services.amount - billing_items.discount)*billing_items.qty) as payables
FROM `billing`
LEFT JOIN `cases` ON `cases`.`id` = `billing`.`case_id`
LEFT JOIN `patients` ON `patients`.`id` = `cases`.`patient_id`
LEFT JOIN `users` ON `users`.`username` = `billing`.`user`
LEFT JOIN `billing_payments` ON `billing_payments`.`billing_id` = `billing`.`id`
LEFT JOIN `billing_items` ON `billing_items`.`billing_id` = `billing`.`id`
LEFT JOIN `services` ON `services`.`title` = `billing_items`.`service`
WHERE `billing`.`is_deleted` =0
To guide you more with my present problem, this is the schema of the related tables:
and this is the schema of the entire database.