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



嗨,在我的代码下面:

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。你们能帮我吗?

你应该只更改一下你的 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

相关内容

  • 没有找到相关文章

最新更新