如何在一个表MySQL中对相同(参数)记录进行求和

时间:2017-08-25 12:11:24

标签: mysql parameters count sum

嗨,就在我的代码下方:

DROP TABLE if exists project_has_tasks;

CREATE TABLE project_has_tasks (`project_id`int(6),`milestone_id` int(6), `status` varchar(100), `value` int(6));

INSERT INTO project_has_tasks (`project_id`, `milestone_id`, `status`, `value`) VALUES 
(56,1, 'undone', 56),
(56,1, 'done', 25),
(56,2, 'done', 25),
(56,3, 'done', 25),
(56,3, 'done', 25),
(56,4, 'undone', 25);


SELECT `milestone_id`, sum(value), 
CASE WHEN (status !='done') 
THEN (value ='0') ELSE sum(value) END as val 
FROM project_has_tasks WHERE project_id='56' 
AND milestone_id !=0 GROUP BY milestone_id ASC 

结果:

 milestone_id | sum(value) | val
 1            | 81         | 0
 2            | 25         | 25
 3            | 50         | 50
 4            | 25         | 0

所有内容看起来都很好,但我想总结任务完成和撤消的记录,以便正确的结果看起来像这样:

 milestone_id | sum(value) | val
 1            | 81         | 25
 2            | 25         | 25
 3            | 50         | 50
 4            | 25         | 0

所以milestone_id = 1应该等于25',因为我在表中有两个。一个是撤消(56),第二个是25(完成)所以结果应该是25.你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

您应该只更改CASE声明:

SELECT `milestone_id`, sum(value), 
SUM(CASE WHEN (status !='done') THEN 0 ELSE value END) as val 
FROM project_has_tasks WHERE project_id='56' 
AND milestone_id !=0 GROUP BY milestone_id ASC 

输出:

    milestone_id    sum(value)  val
1   1   81  25
2   2   25  25
3   3   50  50
4   4   25  0