INSERT INTO payments (created_at, updated_at, deleted_at, booking_id, amount, payment_method) SELECT MIN(i.created_at) AS created_at, -- Use the earliest created_at timestamp for this payment MAX(i.updated_at) AS updated_at, -- Use the latest updated_at timestamp for this payment i.deleted_at, -- Use the deleted_at timestamp from items i.booking_id, -- The associated booking_id SUM(i.price * i.quantity) AS amount, -- Calculate total amount from price * quantity i.payment_method -- The payment method FROM items i WHERE i.deleted_at IS NULL -- Exclude soft-deleted items GROUP BY i.booking_id, i.payment_method, i.deleted_at;