3

我有一张这样的表(简化):

+------+--------+
| 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
+------+--------+

要清楚,

  1. 我有不连续的刻度值并想插入缺失的刻度。
  2. 我想对另一个表执行此操作,因此不会修改原始表。
  3. value缺失s 的 s从前一个现有刻度到下一个现有刻度以相等的步长tick增加/减少。作为一个伪公式:
    increment = (next_value - current_value) / (next_tick - current_tick)

如何管理这个?

4

2 回答 2

4

此存储过程将执行您想要的操作,填充表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

在指示处添加初始刻度和值,如果没有刻度 = 1 的行,则需要它们

于 2012-09-04T14:41:07.870 回答
0

首先你创建一个数字表

Create Table ALL_NUMBERS (
   N Integer
)

Alter table ALL_NUMBERS add primary key (n);

然后将数字表从 1 填充到一个大数字,比如 1 百万

然后 Left 将您的数据表与此数字表连接并填补空白..

于 2012-09-04T14:03:40.310 回答