full code for processing events into reducedEvents and mergin with SQL