简体   繁体   中英

How would I write a SQL Function to Update Store Averages upon INSERT to transactions table?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM