SQLite trigger for updating consolidated accounts

Consider the following two (hypothetical) tables

Temperature

* day
* time
* lake_name
* station
* temperature_f

Temperature_summary

* day
* lake_name
* station
* count_readings_over_75f
* count_readings_below_75f

How can I write an SQLite trigger to update the temperature_summary table for insertion. I want to increase the score.

Thanks Jeff

+3
source share
2 answers

It is assumed that you have already created an entry for day / lake / name / station before inserting temperatures on that day. Of course, you can add another trigger for this.

create trigger Temperature_count_insert_trigger_hi after insert on Temperature
  when new.temperature_f >= 75
  begin
    update Temperature_summary set count_readings_over_75f = count_readings_over_75f + 1
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

create trigger Temperature_count_insert_trigger_lo after insert on Temperature
  when new.temperature_f < 75
  begin
    update Temperature_summary set count_readings_below_75f = count_readings_below_75f + 1
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

You can combine them into one more complex trigger.

create trigger Temperature_count_insert_trigger after insert on Temperature
  begin
    update Temperature_summary
    set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75),
      count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75)
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;

, Temperature_summary (a), Temperature_summary (day, lake_name, station) (b) :

create trigger Temperature_count_insert_trigger after insert on Temperature
  begin
    insert or ignore into Temperature_summary
      values (new.day, new.lake_name, new.station, 0, 0);
    update Temperature_summary
    set count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75),
      count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75)
    where new.day = day and new.lake_name = lake_name and new.station = station;
  end;
+6

. , , .

create trigger Temperature_count_insert_trigger_lo after insert on Temperature    begin 
    update Temperature_summary set Temperature_summary set count_readings_over_75f = count_readings_over_75f + (new.temperature_f >= 75 ), count_readings_below_75f = count_readings_below_75f + (new.temperature_f < 75)
    where new.day = day and new.lake_name = lake_name and new.station = station;    end;

, , .

0

Source: https://habr.com/ru/post/1746269/


All Articles