首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >SQL查询中的累加列

SQL查询中的累加列
EN

Stack Overflow用户
提问于 2011-11-03 22:22:01
回答 2查看 2.7K关注 0票数 1

我有一个相当复杂的查询(执行大约需要30秒),它返回以下数据集:

代码语言:javascript
运行
复制
 Month     Buy     Sell
2010/10     1        2
2010/11     1        3
2010/12     2        5

下面是查询:

代码语言:javascript
运行
复制
select month, avg(buy) [buy], avg(sell) [sell] from products group by month order by month

现在我想添加两个累加的列,预期的结果集如下:

代码语言:javascript
运行
复制
 Month   Ac. Buy   Ac. Sell
2010/10     1          2
2010/11     2          5
2010/12     4          10

我正在尝试使用这个查询

代码语言:javascript
运行
复制
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,我无法更改)。所以我觉得我开的是法拉利,只用了一档。);

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-11-03 22:35:01

对于13行,我只是将中间结果物化到一个表变量中,然后对其进行三角连接。

代码语言:javascript
运行
复制
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
票数 2
EN

Stack Overflow用户

发布于 2011-11-03 22:46:17

看过这个之后,我认为您可能会从CTE中受益(假设您可以使用Com Level设置为80的CTE)。

从收集原始数据的CTE开始,然后将cte结果与自身连接起来,以便能够对平均值求和:

代码语言:javascript
运行
复制
;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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7996467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档