【问题标题】:SQL sum of columns in CodeigniterCodeigniter 中列的 SQL 总和
【发布时间】:2018-06-05 23:44:17
【问题描述】:

我有一个如下的 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 动态获取 AMOUTS 的总和。所需的输出是:

>sum of prodcut_id 5 = 300

>sum of prodcut_id 10 = 400

【问题讨论】:

  • 您可以重新格式化您的问题吗?使其更具可读性。
  • 您正在寻找GROUP BY。你还在使用 MySQL 还是 SQL 服务器?
  • 我更喜欢在 sql 本身中执行此操作。 select PRODUC_ID,sum(AMOUNT) from yourtable group by PRODUC_ID 在 codeigniter 中使用这个结果

标签: php mysql sql-server codeigniter


【解决方案1】:

使用 group by 对金额求和。

剪切-n-粘贴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】:

    试试这样:

    $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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多