Codeigniter中SQL的SQL总和

时间:2017-12-23 22:13:12

标签: php mysql sql-server codeigniter

我有一个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

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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();