mysql - 获取每个名称的总成本之和

标签 mysql sql

I'm trying to get the following result in mysql with below table: I have tried to use sum (case when) but it give me the result for an individual name only ,I want in the report the the total cost for each user.

注意: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                      |
+------------+---------------------------+

最佳答案

查询

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

关于mysql - 获取每个名称的总成本之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32410353/

相关文章:

sql - 如何将值列表传递给一个 Oracle Report 参数?

sql - 从日期时间 SQL 中提取时间

MySQL 插入 ISO8601 日期时间格式

php - 无法更改数据库表

python - 使用 web2py 将 BLOB 保存到 MySQL

mysql left join by max autoincrement id?

php - CodeIgniter:从数据库(表)填充表(HTML/表单)

mysql - 执行一批 SQL 行的最快方法

mysql - mySQL 中内连接和外连接的混合

mysql - 无法退出不正确的 mySQL 命令行