2015-10-05 64 views
2

的SQL Statment我已經user_id = 23,我要查詢,我也有一個表work_log包括project_iduser_idlog_hours這樣的:SUM行與條件

+----+------------+---------+-----------+ 
| 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語句有結果?

+0

你試過自​​己寫嗎? –

+0

是的,我試過了,但沒有奏效。下面的答案適合我 – Francis

+2

如果下面的答案是正確的,請將其標記爲答案。它可以幫助別人。 – pedram

回答

7

這應做到:

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

要顯示與和所有的記錄,只是簡單地去掉where條件。

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