I wanted to get summation of a column's value Grouping by another column using Codegniter framework. on model which name is action, i have used this method:
public function read_sum_groupby($table, $column,$groupBy,$where=array()){
$this->db->group_by($groupBy);
$this->db->where($where);
$this->db->select_sum($column);
$result = $this->db->get($table);
return $result->result();
}
and then i called that method on view like this
$installment_discount = $this->action->read_sum_groupby("installment","discount","installment_id",array("loan_id"=>$loan->id));
and then i printed the output like this
<pre>
<?php print_r($installment_discount); ?>
</pre>
Result was
you can see the last value is 800 but my expected was 200.
my table was
The installment_id of 11,12,13,14 rows are all 7759702. So if you group by installment_id then select_sum(discount), the sql will be like this:
SELECT sum(discount) FROM installment WHERE loan_id=1 GROUP BY installment_id;
the discount of 11,12,13,14 rows will sum up, so you get 800.
if you want to get 200, the sql should be this:
SELECT sum(distinct(discount)) FROM installment WHERE loan_id=1 GROUP BY installment_id;
your code can be written like this:
$this->db->select_sum("distinct($column)", $column);