搜尋
首頁資料庫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整合開發工具