获取每个名称的总成本的总和

时间:2015-09-05 06:51:09

标签: mysql sql

  

我正在尝试使用下表在mysql中获得以下结果:I   我曾试图使用sum (case when),但它给了我一个结果   仅限个人姓名,我希望在报告中每个人的总费用   用户。

注意:ID列不重要,您可以忽略它。

mysql> select * from calls_records;

+----+-------+------------+------+
| id | month | name       | cost |
+----+-------+------------+------+
|  1 | 1     | osama      |   40 |
|  2 | 1     | rahman     |   40 |
|  3 | 1     | ahmed      |   30 |
|  4 | 1     | ali albann | 10.5 |
|  5 | 2     | osama      |   10 |
|  6 | 2     | ali albann |   30 |
|  7 | 2     | ahmed      |   10 |
|  8 | 2     | rahman     |   10 |
+----+-------+------------+------+

预期结果

+-----------+---------------------------+
| name       | total_cost_for_each_user  |
+------------+---------------------------+
| ahmed      |   50                      |
| ali albann | 40.5                      |
| osama      |   50                      |
| rahman     |   50                      |
+------------+---------------------------+

1 个答案:

答案 0 :(得分:2)

<强>查询

select name, sum(cost) as totalcost
from calls_records
group by name
;

<强>输出

+------------+-----------+
|    name    | totalcost |
+------------+-----------+
| ahmed      | 40        |
| ali albann | 40.5      |
| osama      | 50        |
| rahman     | 50        |
+------------+-----------+

sqlfiddle