我有一张这样的表(简化):
+------+--------+
| tick | value |
+------+--------+
| 1 | 10 |
| 2 | 20 |
| 5 | 50 |
| 7 | 10 |
| 10 | 85 |
+------+--------+
我想生成另一个表,其中包含min(tick)
到max(tick)
的所有数字作为刻度值:
+------+--------+
| tick | value |
+------+--------+
| 1 | 10 | * already exists
| 2 | 20 | * already exists
| 3 | 30 | = 20 + 10
| 4 | 40 | = 30 + 10
| 5 | 50 | = 40 + 10 * already exists
| 6 | 30 | = 50 - 20
| 7 | 10 | = 30 - 10 * already exists
| 8 | 35 | = 10 + 25
| 9 | 60 | = 35 + 25
| 10 | 85 | = 60 + 25 * already exists
+------+--------+
要清楚,
value
s缺失tick
s的增加/减少为等于从先前现有的tick到下一个现有的tick。作为一个psudo公式:increment = (next_value - current_value) / (next_tick - current_tick)
如何管理?
答案 0 :(得分:3)
此存储过程将执行您想要的操作,填充表allticks
CREATE PROCEDURE `tickster`()
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE oldticks INT DEFAULT 0; -- initial ticks here
DECLARE oldvalue INT DEFAULT 0; -- initial value here
DECLARE newticks INT DEFAULT 0;
DECLARE newvalue INT DEFAULT 0;
DECLARE t INT DEFAULT 0;
DECLARE v INT DEFAULT 0;
DECLARE delta INT DEFAULT 0;
DECLARE existing CURSOR FOR SELECT ticks,value FROM ticks ORDER BY ticks;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished=1;
OPEN existing;
nexttick: LOOP
-- Get next value or break
FETCH existing INTO newticks,newvalue;
IF finished>0 THEN
LEAVE nexttick;
END IF;
-- initialize a loop to cover the inexistant ticks
SET t=oldticks+1;
SET v=oldvalue;
SET delta=(newvalue-oldvalue)/(newticks-oldticks);
-- run the loop
nextstep: LOOP
IF t>=newticks THEN
LEAVE nextstep;
END IF;
-- calculate new interpolated value and write it to the table
SET v=v+delta;
INSERT INTO allticks SET ticks=t, value=v;
SET t=t+1;
END LOOP;
-- write the existing value to the table
INSERT INTO allticks SET ticks=newticks, value=newvalue;
-- make new dataset the old dataset
SET oldticks=newticks;
SET oldvalue=newvalue;
END LOOP;
END
如果没有带ticks = 1的行,则在指定的位置添加初始刻度和值,如果没有行,则需要它们
答案 1 :(得分:0)
首先创建一个数字表
Create Table ALL_NUMBERS (
N Integer
)
Alter table ALL_NUMBERS add primary key (n);
然后将数字表从1填充到一个大数字,如1百万
然后左边用这个数字表加入你的数据表并填补空白..