从两个表中选择并求和qty(mysql)

时间:2017-09-15 12:39:25

标签: mysql sql join count sum

我想总结一下这样的事情: 我的第一个表只显示项目:

  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%。

2 个答案:

答案 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

答案 1 :(得分: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';