Sql-Server

視窗函式:Rows Unbounded Preceeding 的目的是什麼?

  • May 28, 2019

在視窗函式中使用 Rows Unbounded Preceeding 子句的目的是什麼?我想我理解它基本上是說在匯總函式時不要限制回溯多遠,但這與根本不使用子句有什麼不同?

您能否提供一個範例來說明以下之間的區別:

SUM(ColumnA) OVER (PARTITION BY ColumnB ORDER BY ColumnC DESC ROWS UNBOUNDED PRECEEDING)

SUM(ColumnA) OVER (PARTITION BY ColumnB ORDER BY ColumnC DESC)

注意:我的問題是在以下行沒有上限的情況下。

行和範圍之間的語義差異

如果我們查看此查詢的結果,很容易看出我們何時可能想要檢查使用範圍或行。

SELECT   OwnerUserId,
        CAST(CreationDate AS DATE) AS DumbedDownDate,
        Score,
        SUM(Score) OVER 
                  ( ORDER BY CAST(CreationDate AS DATE)) AS Not_Specified,
        SUM(Score) OVER 
                  ( ORDER BY CAST(CreationDate AS DATE) RANGE UNBOUNDED PRECEDING ) AS Range_Specified,
        SUM(Score) OVER 
                  ( ORDER BY CAST(CreationDate AS DATE) ROWS UNBOUNDED PRECEDING ) AS Rows_Specified
FROM     dbo.Posts
WHERE    OwnerUserId = 1
AND      CAST(CreationDate AS DATE) BETWEEN '2008-08-01' AND '2008-08-31'
ORDER BY DumbedDownDate;

當沒有設置邊界時,結果與我們特別要求 a 相同RANGE。請求ROWS給了我們一個不同的結果。

結果ROWS更像是一個執行總計,RANGE結果是…行範圍的總值。

堅果

表現

如果使用行,則視窗假離線操作員可以使用記憶體中的工作表。Range 使用磁碟工作表,有時速度較慢。

比較這兩個查詢:

SELECT   OwnerUserId,
        CreationDate,
        Score,
        SUM(Score) 
            OVER ( ORDER BY CreationDate RANGE UNBOUNDED PRECEDING ) AS Range_Specified
FROM     dbo.Posts
WHERE    OwnerUserId <= 22656
AND      CreationDate >= '20080101' 
AND      CreationDate < '20150101'
ORDER BY CreationDate;


SELECT   OwnerUserId,
        CreationDate,



        Score,
        SUM(Score) 
            OVER ( ORDER BY CreationDate ROWS UNBOUNDED PRECEDING ) AS Rows_Specified
FROM     dbo.Posts
WHERE    OwnerUserId <= 22656
AND      CreationDate >= '20080101' 
AND      CreationDate < '20150101'
ORDER BY CreationDate;

他們的查詢計劃顯示了 Window Spool 的完全不同的時間:

堅果

如果我們查看兩個查詢的 STATISTICS IO 輸出,它們也有很大不同:

Table 'Worktable'. Scan count 1363952, logical reads 11944334, physical reads 0, 
read-ahead reads 3884, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Posts'. Scan count 5, logical reads 4722714, physical reads 0, read-ahead 
reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

對比

Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, 
read-ahead reads 3884, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Table 'Posts'. Scan count 5, logical reads 4723890, physical reads 0, 
read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

批處理模式

在 SQL Server 2019 中,批處理模式通常可用於行儲存查詢,或 SQL Server 2016/2017,其中有多種方法可以將批處理模式處理引入行儲存查詢,由於添加了批處理模式視窗聚合。

請在此處查看 Itzik Ben-Gan 先生的三部分系列:

引用自:https://dba.stackexchange.com/questions/239168