Question

First I created two tables:

CREATE TABLE min_data(
id integer primary key,
ic char(5) not null,
dt datetime not null,
cou float,
max float not null,
avg float not null,
min float not null);

CREATE TABLE min_data(
id integer primary key,
ic char(5) not null,
dt datetime not null,
cou float,
max float not null,
avg float not null,
min float not null);
CREATE UNIQUE INDEX in_ic_dt on hour_data(ic, dt);

Then I created a trigger as follows.

create trigger ins after insert on min_data
begin
    replace into hour_data(ic, dt, cou, max, avg, min) 
    select ic, strftime('%Y-%m-%d %H:00:00', dt), AVG(cou) * 6, MAX(max), AVG(avg), MIN(min) from min_data where strftime('%Y-%m-%d %H:00:00', new.dt) <= dt and dt < strftime('%Y-%m-%d %H:00:00', new.dt, '+1 hour') and ic = new.ic;
end;

Here is the problem. After I inserted some records into min_data, the trigger would insert some records into hour_data, but the id of records in hour_data doesn't begin with 1 and is discrete. How can I fix the problem?

Was it helpful?

Solution

REPLACE does not update an existing record; it simply deletes any old record, and then inserts a new one.

You have to do the UPDATE or INSERT by hand:

CREATE TRIGGER ...
BEGIN
    -- update the old record, if it already exists:
    UPDATE hour_data
    SET cou = (SELECT AVG(cou) * 6 ...),
        max = (SELECT MAX(max) ...),
        ...
    WHERE ic = NEW.ic
      AND dt = strftime('%Y-%m-%d %H:00:00', NEW.dt);

    -- insert the new record,
    INSERT INTO hour_data(...)
    SELECT ...
    WHERE ...
      -- if it does not yet exist:
      AND NOT EXISTS (SELECT 1
                      FROM hour_data
                      WHERE ic = NEW.ic
                        AND dt = strftime('%Y-%m-%d %H:00:00', NEW.dt));
END;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top