SQL sum of columns in Codeigniter

2019-09-21 14:54发布

问题:

I have a an SQL table as follows:

 >--------------------------  
>|ID | AMOUNT | PRODUC_ID |  
>--------------------------  
>|1  | 100    | 5   
>|2  | 100    | 5  
>|3  | 100    | 5  
>|4  | 100    | 10  
>|5  | 100    | 10  
>|6  | 100    | 10 

>|6  | 100    | 10

Im using codeigniter, Im expecting to get the SUM OF AMOUTS according to the PRODUCT_ID dynamically. the required output is:

>sum of prodcut_id 5 = 300

>sum of prodcut_id 10 = 400

回答1:

Use group by to sum the amounts.

Cut-n-pasted from here.

$query = $this->db->query('select produc_id, sum(amount) as total_amt from mytable group by produc_id');

foreach ($query->result() as $row)
{
    echo $row->produc_id;
    echo $row->total_amt;
}


回答2:

Try like this:

$this->db->select('PRODUC_ID, SUM(AMOUNT) AS AMOUNT', FALSE);
$this->db->group_by('PRODUC_ID');
$query = $this->db->get('TABLE_NAME');
$result = $query->result();