Search code examples
performancet-sqlsql-server-2008-r2cross-apply

CROSS APPLY too slow for running total - TSQL


Please see my code below as it is running too slowly with the CROSS APPLY.

How can I remove the CROSS APPLY and add something else that will run faster? Please note I am using SQL Server 2008 R2.

;WITH MyCTE AS
(
   SELECT 
      R.NetWinCURRENCYValue AS NetWin
     ,dD.[Date]             AS TheDay
   FROM   
      dimPlayer AS P
   JOIN 
      dbo.factRevenue AS R ON P.playerKey = R.playerKey
   JOIN 
      dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
   WHERE    
      P.CustomerID   = 12345)
SELECT 
     A.TheDay               AS [Date]
    ,ISNULL(A.NetWin, 0)    AS NetWin
    ,rt.runningTotal        AS CumulativeNetWin
FROM MyCTE AS A
CROSS APPLY (SELECT SUM(NetWin) AS runningTotal 
                  FROM MyCTE WHERE TheDay <= A.TheDay) AS rt
ORDER BY A.TheDay

Solution

  • CREATE TABLE #temp (NetWin money, TheDay datetime)
    insert into #temp 
    SELECT 
          R.NetWinCURRENCYValue AS NetWin
         ,dD.[Date]             AS TheDay
       FROM   
          dimPlayer AS P
       JOIN 
          dbo.factRevenue AS R ON P.playerKey = R.playerKey
       JOIN 
          dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
       WHERE    
          P.CustomerID   = 12345;
    
    SELECT 
         A.TheDay               AS [Date]
        ,ISNULL(A.NetWin, 0)    AS NetWin
        ,SUM(B.NetWin)          AS CumulativeNetWin
    FROM #temp AS A 
    JOIN #temp AS B 
      ON A.TheDay >= B.TheDay
    GROUP BY A.TheDay, ISNULL(A.NetWin, 0);