How would you optimize a query involving multiple many-to-many joins and group-by operations on a dataset with millions of rows?