56,678
社区成员
发帖
与我相关
我的任务
分享
select id, value,
(select sum(value) from (select value from t_temp where id >= t.id order by id limit 5) b) as s,
(select avg(value) from (select value from t_temp where id >= t.id order by id limit 5) b) as a
from t_temp t where (select count(*) from t_temp where id>=t.id)>=5;
mysql> select * from myricemeli;
+----+-----------+
| id | col_value |
+----+-----------+
| 1 | 35 |
| 2 | 68 |
| 3 | 45 |
| 4 | 71 |
| 5 | 59 |
| 6 | 63 |
| 7 | 25 |
| 8 | 46 |
| 9 | 58 |
+----+-----------+
9 rows in set (0.01 sec)
mysql> select id, col_value,
-> (select sum(col_value) from (select col_value from myricemeli where id>=t.id order by id limit 5) b) as s,
-> (select avg(col_value) from (select col_value from myricemeli where id>=t.id order by id limit 5) b) as a
-> from myricemeli t
-> where (select count(*) from myricemeli where id>=t.id)>=5;
+----+-----------+------+---------+
| id | col_value | s | a |
+----+-----------+------+---------+
| 1 | 35 | 278 | 55.6000 |
| 2 | 68 | 306 | 61.2000 |
| 3 | 45 | 263 | 52.6000 |
| 4 | 71 | 264 | 52.8000 |
| 5 | 59 | 251 | 50.2000 |
+----+-----------+------+---------+
5 rows in set (0.00 sec)
mysql>
BEGIN
DECLARE i int DEFAULT 1;
DECLARE max_ ,min_ ,sum_ ,avg_ int ;
DECLARE ids_ VARCHAR(20) ;
DECLARE count int DEFAULT 0;
SELECT count(*) into count from t_temp ;
WHILE i+5 <= (count+1) DO
SELECT MAX(t.`value`),MIN(t.`value`),SUM(t.`value`),AVG(t.`value`)from t_temp t WHERE t.id in (i,i+1,i+2,i+3,i+4) into max_,min_,sum_,avg_;
SET ids_ = CONCAT_WS(",",i,i+1,i+2,i+3,i+4);
insert into t_temp_view(ids,max,min,sum,avg) values(ids_,max_,min_,sum_,avg_);
SET i = i+1;
end WHILE;
end