I have a fairly complex query (it takes about 30 seconds to execute) that returns me the following dataset:
Month Buy Sell
2010/10 1 2
2010/11 1 3
2010/12 2 5
And here’s the query:
select month, avg(buy) [buy], avg(sell) [sell] from products group by month order by month
Now I want to add two Accumulated Columns and the expected resultset is the following:
Month Ac. Buy Ac. Sell
2010/10 1 2
2010/11 2 5
2010/12 4 10
I’m trying to use this query
select
distinct x.month
,(select SUM(buy) from products where month <= x.month) [Ac Buy]
,(select SUM(sell) from products where month <= x.month) [Ac Sell]
from products X
order by x.month
But that takes way too long!
Is there any way to do this faster?
I’m using a MS SQL 2008 Server, but my compability level is set to 80 (like MSSQL 2000, and I can’t change that). So I feel like I’m driving a Ferrari using only the 1st gear. );
For 13 rows I would just materialise the intermediate results into a table variable then do a triangular join on that.