搜索
首页数据库mysql教程在SQL Server中计算运行总计的最有效方法是什么?

What's the Most Efficient Way to Calculate Running Totals in SQL Server?

SQL Server 累积总和计算方法详解

在SQL查询中计算累积总和是一种常见需求。OVER子句为在Oracle和ANSI-SQL中执行此类计算提供了一种便捷的方法。然而,SQL Server对OVER子句的实现缺乏处理某些用例的灵活性。

更新技巧

尽管存在缺点,但SQL Server中计算累积总和的一个有效技巧是使用聚合集语句。此方法包括:

  1. 创建一个与原始表具有相同列的临时表。
  2. 将原始表中的数据插入到临时表中,同时将累积总和列设置为NULL。
  3. 更新临时表以根据先前值计算累积总和。

此技巧效率很高,但存在潜在问题:

  • UPDATE语句处理行的顺序可能并不总是与日期顺序相同。
  • 更新技巧依赖于SQL Server未公开的实现细节。

基准测试比较

基准测试表明,在SQL Server的约束条件下,游标方法是计算累积总和最快、最安全的方法。更新技巧提供了最高的性能,但存在关于处理顺序的潜在问题。因此,对于生产代码,建议使用基于游标的方法。

示例代码和基准测试数据

以下代码提供了工作示例以及用于基准测试的测试数据:

测试数据设置:

CREATE TABLE #t (
    ord INT PRIMARY KEY,
    total INT,
    running_total INT
);

SET NOCOUNT ON;
DECLARE @i INT;
SET @i = 0;
BEGIN TRAN;
WHILE @i < 10000
BEGIN
    INSERT INTO #t (ord, total) VALUES (@i, ABS(CHECKSUM(NEWID()) % 1000));
    SET @i = @i + 1;
END;
COMMIT TRAN;

测试方法:

测试1:相关子查询

SELECT ord,
       total,
       (SELECT SUM(total)
        FROM #t b
        WHERE b.ord <= a.ord) AS RunningTotal
FROM #t a
ORDER BY a.ord;

测试2:交叉连接

SELECT a.ord,
       a.total,
       SUM(b.total) AS RunningTotal
FROM #t a
CROSS JOIN #t b
WHERE b.ord <= a.ord
GROUP BY a.ord, a.total
ORDER BY a.ord;

测试3:游标

DECLARE @TotalTable TABLE (
    ord INT PRIMARY KEY,
    total INT,
    running_total INT
);

DECLARE forward_cursor CURSOR FAST_FORWARD
FOR
SELECT ord,
       total
FROM #t
ORDER BY ord;

OPEN forward_cursor;

DECLARE @running_total INT,
        @ord INT,
        @total INT;

SET @running_total = 0;

FETCH NEXT FROM forward_cursor
INTO @ord,
      @total;
WHILE (@@FETCH_STATUS = 0)
BEGIN
    SET @running_total = @running_total + @total;
    INSERT @TotalTable VALUES (@ord,
                              @total,
                              @running_total);
    FETCH NEXT FROM forward_cursor
    INTO @ord,
          @total;
END;

CLOSE forward_cursor;
DEALLOCATE forward_cursor;

SELECT *
FROM @TotalTable;

测试4:更新技巧

DECLARE @total INT;
SET @total = 0;
UPDATE #t
SET running_total = @total,
    @total = @total + total;

SELECT *
FROM #t;

通过比较以上四种方法的执行效率,可以得出在SQL Server中计算累积总和的最佳实践。 需要注意的是,实际性能可能因数据量和服务器配置而异。

以上是在SQL Server中计算运行总计的最有效方法是什么?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
如何在MySQL中删除或修改现有视图?如何在MySQL中删除或修改现有视图?May 16, 2025 am 12:11 AM

todropaviewInmySQL,使用“ dropviewifexistsview_name;” andTomodifyAview,使用“ createOrreplaceViewViewViewview_nameAsSelect ...”。whendroppingaview,asew dectivectenciesanduse和showcreateateviewViewview_name;“ tounderStanditSsstructure.whenModifying

MySQL视图:我可以使用哪些设计模式?MySQL视图:我可以使用哪些设计模式?May 16, 2025 am 12:10 AM

mySqlViewScaneFectectialized unizedesignpatternslikeadapter,Decorator,Factory,andObserver.1)adapterPatternadaptSdataForomDifferentTablesIntoAunifiendView.2)decoratorPatternenhancateDataWithCalcalcualdCalcalculenfields.3)fieldfields.3)

在MySQL中使用视图的优点是什么?在MySQL中使用视图的优点是什么?May 16, 2025 am 12:09 AM

查看InMysqlareBeneForsImplifyingComplexqueries,增强安全性,确保dataConsistency,andOptimizingPerformance.1)他们simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

如何在MySQL中创建一个简单的视图?如何在MySQL中创建一个简单的视图?May 16, 2025 am 12:08 AM

toCreateAsimpleViewInmySQL,USEthecReateaTeviewStatement.1)defitEtheetEtheTeViewWithCreatEaTeviewView_nameas.2)指定usethectstatementTorivedesireddata.3)usethectStatementTorivedesireddata.3)usetheviewlikeatlikeatlikeatlikeatlikeatlikeatable.views.viewssimplplifefifydataaccessandenenanceberity but consisterfort,butconserfort,consoncontorfinft

MySQL创建用户语句:示例和常见错误MySQL创建用户语句:示例和常见错误May 16, 2025 am 12:04 AM

1)foralocaluser:createUser'localuser'@'@'localhost'Indidendify'securepassword'; 2)foraremoteuser:creationuser's creationuser'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Remoteer'Rocaluser'@'localhost'Indidendify'seceledify'Securepassword'; 2)

在MySQL中使用视图的局限性是什么?在MySQL中使用视图的局限性是什么?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他们不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinSorsubqueries.2)他们canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

确保您的MySQL数据库:添加用户并授予特权确保您的MySQL数据库:添加用户并授予特权May 14, 2025 am 12:09 AM

porthusermanagementInmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素会影响我可以在MySQL中使用的触发器数量?哪些因素会影响我可以在MySQL中使用的触发器数量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)复杂的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具