【问题标题】:SQL Statement of SUM rows with conditions带有条件的 SUM 行的 SQL 语句
【发布时间】:2015-10-05 08:41:57
【问题描述】:

我有user_id = 23 我想查询,我还有一个表work_log 包括project_iduser_idlog_hours 像这样:

+----+------------+---------+-----------+
| id | project_id | user_id | log_hours |
+----+------------+---------+-----------+
| 1  |    23      |   23    |   2.5     |
| 1  |    3       |   23    |   3       |
| 1  |    23      |   23    |   1       |
| 1  |    24      |   23    |   3       |
| 1  |    24      |   23    |   1.5     |
| 1  |    23      |   23    |   0.5     |
+----+------------+---------+-----------+

但现在我想将每个结果的所有 log_hours 相加:

+------------+------------------+
| project_id | sum_of_log_hours |
+------------+------------------+
|     23     |       4          |
|     3      |       3          |
|     24     |       4.5        |
+------------+------------------+

如何编写 SQL 语句以获得该结果?

【问题讨论】:

  • 你试过自己写吗?
  • 是的,我试过了,但没用。下面的答案适合我
  • 如果以下答案正确,请将其标记为答案。它可以帮助他人。
  • 下面的答案是正确的,您只需要删除过滤where user_id = '23' 以显示所有记录及其log_hours的总和。

标签: mysql sql sum


【解决方案1】:

应该这样做:

Select project_id, sum(log_hours) as sum_log_hours
from work_log
where user_id = '23'
group by project_id

【讨论】:

    【解决方案2】:

    要显示所有带有总和的记录,只需删除where 条件即可。

        SELECT project_id, sum(log_hours) AS sum_log_hours
        FROM work_log GROUP BY project_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-27
      • 2016-01-11
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多