2017-09-15 112 views
1

我想總結是這樣的總和數量: 我的第一個表只顯示項目:選擇並從兩個表(MySQL的)

id |progress [%] | 
    1 |100   | 
    2 |5    | 
    3 |5    | 
    4 |100   | 
    5 |10   | 

第二個表顯示,其中PROJECT_ID具有相同的數字ID的任務第一個表(ID = PROJECT_ID):

Project_id |status  | 
    1   |done  | 
    2   |done  | 
    3   |undone  | 
    4   |in_progress| 
    5   |done  | 

所以我想加入這兩個表,並得到一個行的結果:

| done | undone | in_progress | 
| 2  | 1  | 0   | 

我想總結所有的任務(第二個表)與他們的狀態,但沒有那些在100%進度項目(第一個表)內的任務。

+0

谷歌關於 '支點' –

回答

1

使用SUMCASE陳述。

SELECT SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) done, 
SUM(CASE WHEN status = 'undone' THEN 1 ELSE 0 END) undone, 
SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END) in_progress 
FROM yourtablea a 
INNER JOIN yourtableb b ON a.id = b.Project_id 
WHERE progress != '100' 

輸出

done undone in_progress 
2 1  0 

SQL小提琴:http://sqlfiddle.com/#!9/6b936/2/0

0
select SUM(if(a.status ="done", 1,0)) as `Done`, SUM(if(a.status ="undone", 1,0)) as `UnDone`, SUM(if(a.status ="in_progress", 1,0)) as `UnDone` from Status_table a join Progress_table b on a.Project_id = b.id WHERE b.progress != '100';