Search code examples
sql-servert-sqlquery-optimizationranking

Same window function in multiple fields in T-SQL: optimization?


I am using the very same windowing function in multiple WHEN in a T-SQL SELECT.

SELECT 
    ModuleUsage = CASE
        WHEN Operation = 1 and OperationResult=1 and 1 != LAG(operation) OVER(
            PARTITION BY moduleid, clientname
            ORDER BY moduleid, clientname, timestamp, operation
        )
            THEN 1
        WHEN Operation = 2 and OperationResult=3 and 1 = LAG(operation) OVER(
            PARTITION BY moduleid, clientname
            ORDER BY moduleid, clientname, timestamp, operation
        )
            THEN -1
        ELSE 0
    END
    , *
FROM [dbo].[LicencesTracing]

Is it evaluated twice or does the query optimizer reuse the result the second time? Thanks in advance


Solution

  • Could we rewrite the query like below in order to have the function only one time?

           -- window function <> 1
    SELECT CASE WHEN LAG(operation) OVER(PARTITION BY moduleid, clientname ORDER BY moduleid, clientname, timestamp, operation) <> 1
    
                THEN CASE WHEN Operation = 1 and OperationResult=1 THEN 1 ELSE 0 END
    
           -- window function = 1
           ELSE
    
                CASE WHEN Operation = 2 and OperationResult=3 THEN -1 ELSE 0 END
           END AS ModuleUsage
          ,*
    FROM [dbo].[LicencesTracing];
    

    And I thing using IIF will simplify the code:

    SELECT CASE WHEN LAG(operation) OVER(PARTITION BY moduleid, clientname ORDER BY moduleid, clientname, timestamp, operation) <> 1 
                THEN IIF(Operation = 1 and OperationResult=1, 1, 0)
                ELSE IIF(Operation = 2 and OperationResult=3, -1, 0)
           END AS ModuleUsage
          ,*
    FROM [dbo].[LicencesTracing];