• First tip: if you put all of that in a code block it will give a seperate scrollbar and not make your page so long and hard to read.

    At first blush ... it is likely the distincts which are killing your performance. I'll edit later if I have a better suggestion. Edit: actually, the number of windowing functions doesn't help either