我有一个相当复杂的查询(执行大约需要30秒),它返回以下数据集:
Month Buy Sell
2010/10 1 2
2010/11 1 3
2010/12 2 5
这是查询:
select month, avg(buy) [buy], avg(sell) [sell] from products group by month order by month
现在我想添加两个累积列,预期的结果集如下:
Month Ac. Buy Ac. Sell
2010/10 1 2
2010/11 2 5
2010/12 4 10
我正在尝试使用此查询
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
但这需要太长时间!
有没有办法更快地做到这一点?
我正在使用MS SQL 2008 Server,但我的兼容级别设置为80(就像MSSQL 2000一样,我无法改变它)。所以我觉得我只使用一档驾驶法拉利。 );
答案 0 :(得分:2)
对于13行,我只是将中间结果表示为表变量,然后对其进行三角形连接。
DECLARE @Results TABLE
(
Month char(7) PRIMARY KEY,
Buy int,
Sell int
)
INSERT INTO @Results /*Your select query goes here*/
SELECT '2010/10',1,2 UNION ALL
SELECT '2010/11',1,3 UNION ALL
SELECT '2010/12',2,5
SELECT R1.Month,
R1.Buy,
R1.Sell,
SUM (R2.Sell)AS AcSell,
SUM (R2.Buy) AS AcBuy
FROM @Results R1
JOIN @Results R2 ON R2.Month <= R1.Month
GROUP BY R1.Month,
R1.Buy,
R1.Sell
答案 1 :(得分:2)
看了这个,我想你可能会从CTE中受益(假设你可以使用Com Level设置为80的那些......)
从收集原始数据的CTE开始,然后将cte结果加入到自身,以便能够将平均值相加:
;with productsCTE
as
(
-- Original query!
select month, AVG(buy) buy, AVG(sell) sell
from products
group by mnth
)
select
p1.month,
p1.buy,
SUM(p2.buy) sumavgbuy,
p1.sell,
SUM(p2.sell) sumavgsell
from productsCTE p1
inner join productsCTE p2 on p2.month <= p1.month
group by p1.month,p1.buy,p1.sell