计算每个id的累计/增加[MYSQL]

时间:2017-10-03 20:17:08

标签: mysql sum cumulative-sum

我想从下表(table_values)计算每条记录的增加值:

  id | open | closed | in_progress | project |
  1  | 0    | 0      | 0           | 20      | 
  2  | 1    | 0      | 1           | 20      |
  3  | 1    | 1      | 1           | 55      | 
  4  | 1    | 1      | 1           | 20      | 
  5  | 1    | 1      | 1           | 20      | 
  6  | 2    | 2      | 0           | 20      | 

例如,选择project = 20的位置 结果应该是:

 id | open | closed | in_progress | project | Total |
 1  | 0    | 0      | 0           | 20      |  0    |
 2  | 1    | 0      | 1           | 20      |  2    |
 4  | 2    | 1      | 2           | 20      |  3    |
 5  | 3    | 2      | 3           | 20      |  3    |
 6  | 5    | 4      | 3           | 20      |  4    |

如果可能,选择应返回每个ID的累积结果。 有什么建议吗?

问候。

更新: 表:

  id | open | 
  1  | 2    |
  2  | 3    |
  3  | 5    | 

结果:

  id | open | cumulative_open
  1  | 2    | 2
  2  | 3    | 5
  3  | 5    | 10

2 个答案:

答案 0 :(得分:2)

您可以使用同一项目中的所有先前(包括相同)行加入行,并使用SUM()

select t1.id,
    sum(t2.open) as open,
    sum(t2.closed) as closed,
    sum(t2.in_progress) as in_progress,
    t1.project,
    t1.open + t1.closed + t1.in_progress as Total
from table_values t1
join table_values t2
  on  t2.project = t1.project
  and t2.id <= t1.id
where t1.project = 20
group by t1.id

演示:http://rextester.com/NZDN42998

这是一个昂贵的查询(在性能方面) - 但至少它是可靠的。

答案 1 :(得分:1)

此方法使用参数和外观来实现您所描述的内容。你可能想要修改名称,因为有些可能有点不合适(因为它们对保留名称不熟)

SET @open = 0;
SET @closed = 0;
SET @in_progress = 0;
select 
id,
(@open := @open + open) as open,
(@closed := @closed + closed) as closed,
(@in_progress := @in_progress + in_progress) as in_progress,
project,
(open + closed + in_progress) as Total
FROM table_values
where project = 20
group by id;