Reputation: 1
CREATE OR REPLACE FUNCTION update_summary_table()
RETURNS TRIGGER AS $$
BEGIN
-- Insert or update the summary table with aggregated data
INSERT INTO summary_table (movie_title, total_rentals, total_revenue, average_rental_duration, rental_month)
VALUES (
NEW.movie_title, -- New movie title
1, -- Initial rental count
NEW.payment_amount, -- Initial revenue
EXTRACT(DAY FROM NEW.return_date - NEW.rental_date), -- Rental duration in days
DATE_TRUNC('month', NEW.rental_date) -- Rental month
)
ON CONFLICT (movie_title, rental_month) -- Handle conflicts for the same movie and month
DO UPDATE
SET
total_rentals = summary_table.total_rentals + 1, -- Increment rental count
total_revenue = summary_table.total_revenue + NEW.payment_amount, -- Add to total revenue
average_rental_duration = (
(summary_table.average_rental_duration * summary_table.total_rentals + EXTRACT(DAY FROM NEW.return_date - NEW.rental_date))
/ (summary_table.total_rentals + 1) -- Recalculate average duration
);
-- Return the new row to allow the trigger to proceed
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Verified all column names match. not sure what else to try.
Exact Error:
Upvotes: 0
Views: 54