db_table => commitment
ref_no | comm_date |
---|---|
1 | 2022-10-05 |
2 | 2022-10-05 |
3 | 2022-10-06 |
4 | 2022-10-07 |
5 | 2022-10-07 |
6 | 2022-10-08 |
db_table => collection
ref_no | amount | trnx_date |
---|---|---|
1 | 500 | 2022-10-05 |
2 | 100 | 2022-10-05 |
1 | 700 | 2022-10-06 |
3 | 400 | 2022-10-07 |
3 | 600 | 2022-10-08 |
5 | 800 | 2022-10-08 |
1 | 700 | 2022-10-08 |
I want to achieve something like this in datatable:
ref_no | comm_date | collection summary |
---|---|---|
1 | 2022-10-05 | 500 (2022-10-05) + 700 (2022-10-06) + 700 (2022-10-08) = 1900 |
2 | 2022-10-05 | 100 (2022-10-05) = 100 |
3 | 2022-10-06 | 400 (2022-10-07) + 600 (2022-10-08) = 1000 |
4 | 2022-10-07 | 0 |
5 | 2022-10-07 | 800 (2022-10-08) = 800 |
6 | 2022-10-08 | 0 |
How can I achieve this with php and mysql and show it to datatable. Thanks in advance!
What I have tried in sql in codeigniter model:
SELECT c.*, t.*
FROM commitment c
LEFT JOIN collection t ON c.ref_no = t.ref_no
WHERE c.ref_no IN (SELECT ref_no FROM collection)
GROUP BY c.ref_no
In controller:
public function collection_statement_list() {
// Datatables Variables
$draw = intval($this->input->get("draw"));
$start = intval($this->input->get("start"));
$length = intval($this->input->get("length"));
$fetch = $this->Project_model->get_collection_statement();
$data = array();
foreach($fetch->result() as $r) {
$ref_no = $r->ref_no;
$comm_date = $this->Project_model->set_date_format($r->comm_date);
$coll_date = $this->Project_model->set_date_format($r->trnx_date);
$coll_summary = $r->amount.'<span class="text-primary"><small>('.$coll_date.')</small></span>';
$data[] = array(
$ref_no,
$comm_date,
$coll_summary,
);
}
$output = array(
"draw" => $draw,
"recordsTotal" => $fetch->num_rows(),
"recordsFiltered" => $fetch->num_rows(),
"data" => $data
);
echo json_encode($output);
exit();
}
And the output in datatable is:
| ref_no | comm_date | collection summary |
| —— | ———- | —————— |
| 1 | 2022-10-05 | 500 (2022-10-05) |
| 2 | 2022-10-05 | 100 (2022-10-05) |
| 3 | 2022-10-06 | 400 (2022-10-07) |
| 4 | 2022-10-07 | 0 |
| 5 | 2022-10-07 | 800 (2022-10-08) |
| 6 | 2022-10-08 | 0 |
2
Answers
I think such way. Imagine you have a table about amounts. It is will be solution by sql:
However you may use alternative way to be group with php such:
And so in SQL only this query corresponds to your solution with group_concat…? I’m trying to answer to help those who would be looking for the solution in SQL only.