SQL Server 累積總和運算方法詳解
在SQL查詢中計算累積總和是一種常見需求。 OVER
子句為在Oracle和ANSI-SQL中執行此類計算提供了一種便捷的方法。然而,SQL Server對OVER
子句的實作缺乏處理某些用例的彈性。
更新技巧
儘管有缺點,但SQL Server中計算累積總和的一個有效技巧是使用聚合集語句。此方法包括:
- 建立一個與原始表具有相同列的臨時表。
- 將原始表中的資料插入臨時表中,同時將累積總和列設為NULL。
- 更新臨時表以根據先前值計算累積總和。
此技巧效率很高,但有潛在問題:
-
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中文網其他相關文章!

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

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

查看InMysqlareBeneForsImplifyingComplexqueries,增強安全性,確保dataConsistency,andOptimizingPerformance.1)他們simimplifycomplexqueriesbleiesbyEncapsbyEnculatingThemintoreusableviews.2)viewsEnenenhancesecuritybyControllityByControllingDataAcces.3)

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

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)

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

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

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


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1
強大的PHP整合開發環境

WebStorm Mac版
好用的JavaScript開發工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

SublimeText3漢化版
中文版,非常好用

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具