Reputation: 5
I am attempting to create a SQL trigger function that should UPDATE a secondary table when data is INSERTED into the original table. The update would be based on the amount and store_id columns.
I have the following table to store every transaction that has happened at both stores being represented.
CREATE TABLE transactions(
payment_id INT NOT NULL PRIMARY KEY,
payment_date TIMESTAMP NOT NULL,
store_id INT NOT NULL,
amount FLOAT NOT NULL
);
When an insert is completed, I want my store_averages table to have the averages that are represented updated, as well. This table was created like so: (note: there are only 2 stores being tracked in these tables)
CREATE TABLE store_averages AS
SELECT transactions.store_id, avg(transactions.amount)
FROM transactions
WHERE transactions.store_id=1
GROUP BY transactions.store_id;
INSERT INTO store_averages
SELECT transactions.store_id, avg(transactions.amount)
FROM transactions
WHERE transactions.store_id=2
GROUP BY transactions.store_id;
In my testing, I have been able to update the values from a trigger for one store, but not both. How would I do this?
Upvotes: 0
Views: 48
Reputation: 603
I doubt you want to keep inserting values with no other information to your store_averages table, as there's nothing present to indicate which is most current. If the intent is to have a table that contains only the most current store averages following each transaction, I'd ask a few more questions that may be fit for purpose - such as frequency of updates occurring, and whether this needs to be real-time updates or perhaps just maintained hourly / daily.
My initial thought would be to create a view or materialized view for this information ...
Upvotes: 1