• To add to what Usman and Gail have recommended, the Udf_convert_int_date is likely a scalar function (according to the way you used it). That's going to make life slower to begin with. Using it in a GROUP BY is only going to be another performance problem because of that and the fact that you can GROUP BY the raw integer date even if it's not in the YYYYMMDD format and still end up with the same result but faster.

    I especially agree with Gails recommendation to Divide'n'Conquer this problem through the use of interim results stored in a Temp Table. Aggregate/manipulate first, then display. It will allow you to avoid several of the sum calculations and most of the repeated queries and their related joins. Don't try to do it all in a single query especially since it seems that you may have some accidental many-to-many joins that require the use of DISTINCT.

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)