gpt4 book ai didi

sql-server-2012 - LAG 和 LEAD 函数

转载 作者:行者123 更新时间:2023-12-04 23:59:07 26 4
gpt4 key购买 nike

在 SQL Server 2012 中使用新的 LAG 和 LEAD 函数有哪些优势?
是更容易编写和更简单的调试查询还是性能改进?

这对我来说很重要,因为我们经常需要这种类型的功能,我需要知道我们是否应该在不久的将来推荐升级。
如果只是更简单的查询,那么升级的麻烦(和成本)将不值得。

最佳答案

为了演示执行计划的差异,我使用了 Dave 的 SQL Authority 博客中的获胜解决方案:

  • Solution to Puzzle – Simulate LEAD() and LAG() without Using SQL Server 2012 Analytic Function

  • ;WITH T1
    AS (SELECT row_number() OVER (ORDER BY SalesOrderDetailID) N
    , s.SalesOrderID
    , s.SalesOrderDetailID
    FROM
    TempDB.dbo.LAG s
    WHERE
    SalesOrderID IN (20120303, 20120515, 20120824, 20121031))
    SELECT SalesOrderID
    , SalesOrderDetailID AS CurrentSalesOrderDetailID
    /* , CASE
    WHEN N % 2 = 1 THEN
    max(CASE
    WHEN N % 2 = 0 THEN
    SalesOrderDetailID
    END) OVER (PARTITION BY (N + 1) / 2)
    ELSE
    max(CASE
    WHEN N % 2 = 1 THEN
    SalesOrderDetailID
    END) OVER (PARTITION BY N / 2)
    END LeadVal */
    , CASE
    WHEN N % 2 = 1 THEN
    max(CASE
    WHEN N % 2 = 0 THEN
    SalesOrderDetailID
    END) OVER (PARTITION BY N / 2)
    ELSE
    max(CASE
    WHEN N % 2 = 1 THEN
    SalesOrderDetailID
    END) OVER (PARTITION BY (N + 1) / 2)
    END PreviousSalesOrderDetailID
    FROM
    T1
    ORDER BY
    SalesOrderID
    , SalesOrderDetailID;



    SELECT SalesOrderID
    , SalesOrderDetailID AS CurrentSalesOrderDetailID
    , LAG(SalesOrderDetailID, 1, 0) OVER (ORDER BY SalesOrderID, SalesOrderDetailID) AS PreviousSalesOrderDetailID
    FROM TempDB.dbo.LAG
    WHERE SalesOrderID IN (20120303, 20120515, 20120824, 20121031);





    Warning: Null value is eliminated by an aggregate or other SET operation.

    (10204 row(s) affected)
    Table 'Worktable'. Scan count 6, logical reads 81638, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'LAG'. Scan count 4, logical reads 48, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

    SQL Server Execution Times: CPU time = 297 ms, elapsed time = 332 ms.

    --- versus ---

    (10204 row(s) affected)
    Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
    Table 'LAG'. Scan count 4, logical reads 48, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

    SQL Server Execution Times: CPU time = 78 ms, elapsed time = 113 ms.

    除了更加优雅之外,它还消耗更少的资源。

    下面是图形化执行计划的比较:

    Execution Plans Show Clear Winner in This Specific Case

    在这种特定情况下,执行计划显示了一个明显的赢家。
    Dave 的页面有许多可能的不同方式来获得 LEAD/LAG 功能。也许其中一些会击败 SQL Server 的内部解决方案。或者可能不是。

    关于sql-server-2012 - LAG 和 LEAD 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12953231/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com