|
I have a financial query that uses Sum() multiple times in different calculations. The query is very slow because the sum() function has to rerun multiple times in the query. Is there a way to store the results in a variable and reference the variable later in the query rather that redoing the sum() again? Query follows:
(comments are locked)
|
|
The query is probably slow because of the number of sub-queries, not merely the repetition of the SUM(). I've only had a quick glance at the query, but if you can't change some of the sub-selects into joins, then either a derived table or cte is your way forward, however that will probably just make it more readable, not necessarily any quicker. edit : a quick rehash, but may contain some typos, as I've no real tables to test against What this is demonstrating, is that the base values are calculated only once, and then referenced by their aliases in the outer queries.
(comments are locked)
|
|
You can use tables variables, temp tables, common table expresions aka cte'. A lot of flexibility depending upon a lot of factors. It seems from a quick look at your question that youi're looking for table variables though.
(comments are locked)
|

