为每个 ID [MYSQL] 计数 cumulative/increase

Count cumulative/increase for each id [MYSQL]

我想计算下面每条记录的增加值 table (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      | 

例如 select 其中项目 = 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    |
如果可能,

Select 应该 return 每个 id 的累积结果。 有什么建议吗?

此致。

更新: TABLE:

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

结果:

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

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

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;

您可以将来自同一项目的所有先前(包括相同)行的行连接起来,并使用 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

这是一个昂贵的查询(就性能而言)- 但至少它是可靠的。