我有一个相当复杂的查询(执行大约需要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 SQL2008Server,但我的兼容级别设置为80 (如MSSQL2000,我无法更改)。所以我觉得我开的是法拉利,只用了一档。);
发布于 2011-11-03 22:35:01
对于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
发布于 2011-11-03 22:46:17
看过这个之后,我认为您可能会从CTE中受益(假设您可以使用Com Level设置为80的CTE)。
从收集原始数据的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
https://stackoverflow.com/questions/7996467
复制相似问题