owf
owf

Reputation: 251

Select SUM with Grouping MYSQL

I'm having difficulties to SUM in mysql with grouping from certain field

+------------+----------+----------------------+
| order_plan | subgroup | requested_amount_usd |
+------------+----------+----------------------+
| 2020-07    | SOFTWARE |                10.00 |
| 2020-07    | SOFTWARE |                15.00 |
| 2020-07    | FLASHDISK|                25.00 |
| 2020-08    | SOFTWARE |                10.00 |
+------------+----------+----------------------+

what i've tried to query (using CI) :

$this->db
->distinct('subgroup','order_plan')
->select_sum('requested_amount_usd','requested_amount')
->from($table);
return $this->db->get()->result_array();

the result was looks like this :

+------------------+
| requested_amount |
+------------------+
|           60.00  |
+------------------+

while I was expecting the result would be like this :

+------------+----------+----------------------+
| order_plan | subgroup | requested_amount_usd |
+------------+----------+----------------------+
| 2020-07    | SOFTWARE |                25.00 |
| 2020-07    | FLASHDISK|                25.00 |
| 2020-08    | SOFTWARE |                10.00 |
+------------+----------+----------------------+

How can I achieve that ?

Upvotes: 0

Views: 77

Answers (1)

Raj
Raj

Reputation: 19


SELECT order_plan
     , subgroup
     , SUM(requested_amount_usd) AS requested_amount_usd
  FROM {table} 
 group 
    by subgroup
     , order_plan

Always remember you need to GROUP all the other columns while using SUM(),AVG(),COUNT()

Upvotes: 1

Related Questions