Reputation: 477
I have some problems with creating a trigger that will update values in a second table with average values from the first table. Since i am not very familiar with sqlite statements, maybe you guys can help me.
Here is my problem : i have one table table_1
and another table table_2
What i want is that table_2 "average_value" field to be updated with the average of values from table_1 that have the same field.
In this particular case resulting the aveage_value field in table 2 like this : 5 - for field_a 8 - for field_b 0 - for field_c
Any suggestions will help me alot ! Thank You.
Upvotes: 0
Views: 2772
Reputation: 180210
To compute the average value of a specific field dynamically, use this query:
SELECT AVG(value)
FROM table_1
WHERE field = 'field_a';
If you want instead a view that looks like your table_2
, you can define it like this:
CREATE VIEW view_2 AS
SELECT field,
AVG(value) AS average_value
FROM table_1
GROUP BY field;
If you really want table_2
to be an actual table, you could compute the average values like this:
UPDATE table_2
SET average_value = (SELECT AVG(value)
FROM table_1
WHERE table_1.field = table_2.field);
If you want table_2
to be an actual table, and want to update only those values that have changed, use a trigger like this:
CREATE TRIGGER update_average_value_after_insert
AFTER INSERT ON table_1
FOR EACH ROW
BEGIN
UPDATE table_2
SET average_value = (SELECT AVG(value)
FROM table1
WHERE table1.field = NEW.field)
WHERE field = NEW.field;
END;
(You also need similar triggers for UPDATE
and DELETE
.)
Upvotes: 3