• Without knowing much details, It would be all guess work. Please post DDL of the tables, some data and the required output to get better help.

    But seeing your code I think two things I do not understand

    1. AGRREGATION (SUM, MAX etc) with DISTINCT

    2. GROUPING ON COLUMNS WHICH ARE AGGREGATED

    So look into these, as they could be addding more processing than actually needed.