带有条件的SUM行的SQL语句

时间:2015-10-05 08:41:57

标签: mysql sql sum

我想查询user_id = 23,我还有一个表work_log包含project_iduser_idlog_hours,如下所示:< / p>

+----+------------+---------+-----------+
| 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语句以获得该结果?

2 个答案:

答案 0 :(得分:7)

这应该这样做:

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

答案 1 :(得分:1)

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

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