SQL查询条件累积

时间:2016-07-08 12:35:30

标签: mysql sql

可以显示累计数据,根据条件重置计数吗? 我想创建一个脚本来累积,如果单元格编号中有值1,但如果另一个值应该重新开始计数。类似于cumulative_with_condition列中显示的内容。

+----+------------+--------+
| id | release    | number |
+----+------------+--------+
|  1 | 2016-07-08 | 4      | 
|  2 | 2016-07-09 | 1      | 
|  3 | 2016-07-10 | 1      | 
|  4 | 2016-07-12 | 2      | 
|  5 | 2016-07-13 | 1      | 
|  6 | 2016-07-14 | 1      | 
|  7 | 2016-07-15 | 1      | 
|  8 | 2016-07-16 | 2-3    | 
|  9 | 2016-07-17 | 3      | 
| 10 | 2016-07-18 | 1      | 
+----+------------+--------+

select * from version where id > 1 and id < 9;
+----+------------+--------+---------------------------+
| id | release    | number | cumulative_with_condition |
+----+------------+--------+---------------------------+
|  2 | 2016-07-09 | 1      | 1                         |
|  3 | 2016-07-10 | 1      | 2                         |
|  4 | 2016-07-12 | 2      | 0                         |
|  5 | 2016-07-13 | 1      | 1                         |
|  6 | 2016-07-14 | 1      | 2                         |
|  7 | 2016-07-15 | 1      | 3                         |
|  8 | 2016-07-16 | 2-3    | 0                         |
+----+------------+--------+---------------------------+

2 个答案:

答案 0 :(得分:1)

你想要row_number()之类的东西(不完全是,但是那样)。你可以使用变量来做到这一点:

select t.*,
       (@rn := if(number = 1, @rn + 1,
                  if(@n := number, 0, 0)
                 )
       ) as cumulative_with_condition
from t cross join
     (select @n := '', @rn := 0) params
order by t.id;

答案 1 :(得分:1)

作为使用用户变量的替代方法,如Gordon Linoff所示,在这种情况下,它也可以自我加入,分组和计数:

SELECT   t.id, t.release, t.number, COUNT(version.id) AS cumulative_with_condition
FROM     version RIGHT JOIN (
           SELECT   highs.*, MAX(lows.id) min
           FROM     version lows RIGHT JOIN version highs ON lows.id <= highs.id
           WHERE    lows.number <> '1'
           GROUP BY highs.id
         ) t ON version.id > t.min AND version.id <= t.id
WHERE    t.id > 1 AND t.id < 9
GROUP BY t.id

sqlfiddle上查看。

但是,坦率地说,这两种方法都不是特别优雅 - 正如我之前评论的那样,你可能最好在你的应用程序代码中实现它。