Codeigniter中SQL的SQL总和

问题描述 投票:-2回答:2

我有一个SQL表如下:

 >--------------------------  
>|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

我正在使用codeigniter,我希望动态地根据PRODUCT_ID获得SUM OF AMOUTS。所需的输出是:

>sum of prodcut_id 5 = 300

>sum of prodcut_id 10 = 400
php mysql sql-server codeigniter
2个回答
0
投票

使用group by对金额求和。

切割粘贴的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;
}

0
投票

试试这样:

$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();
© www.soinside.com 2019 - 2024. All rights reserved.