我遇到一個問題產生與我的查詢結果。我想要從與主表相關的另一個表中生成行結果的SUM。SQL加入SUM沒有正常工作
我沒有輸出的是付款總額和應付款總額。
問題#1 - 我無法產生正確的付款輸出。 查詢似乎產生公式
numrows * sum_of_payments
問題#2 - 我無法產生總應付款的產出。
我正在使用Codeigniter 3,這是我的模型。
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;
}
我保存上次查詢和登錄助手的最後一個查詢,它似乎爲我實例的查詢是
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
爲了更引導你用我現在的問題,這是架構相關表格:
,這是整個數據庫的模式。
你是否把選擇和沒有組或可能? –
@martonohalim我做了'$ this-> db-> group_by('billing.id');' –
我不確定代碼點火器是如何工作的,但是您的組似乎沒有足夠的列進行分組。它應該把除了總和列以外的所有列。希望能幫助到你。 –