【问题标题】:Getting the SUM of total cost for each name获取每个名称的总成本总和
【发布时间】:2015-12-01 08:06:48
【问题描述】:

我正在尝试通过下表在 mysql 中获得以下结果:我 曾尝试使用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                      |
+------------+---------------------------+

【问题讨论】:

  • 尝试GROUP BY name
  • 我试过了,但它不会给你每个用户的总费用。
  • 在你的例子中 id 列来自哪里。当你分组时,拥有这个 id 没有意义..
  • 预期输出中的偶数月列没有意义
  • 按名称从calls_records组中选择名称,总和(成本)作为total_cost_for_each_user

标签: mysql sql


【解决方案1】:

查询

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

【讨论】:

    猜你喜欢
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多