4

CROSS APPLY の実行が遅すぎるため、以下のコードを参照してください。

CROSS APPLY を削除して、より高速に実行される何かを追加するにはどうすればよいですか? 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
4

3 に答える 3

0
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);
于 2013-08-29T13:45:46.843 に答える
0

ここで述べたように、非常に高速な計算が必要な場合は、順次主キーを持つ一時テーブルに入れてから、ローリング合計を計算します。

create table #Temp (
    ID bigint identity(1, 1) primary key,
    [Date] date,
    NetWin decimal(29, 10)
)

insert into #Temp ([Date], NetWin)
select
    dD.[Date],
    sum(R.NetWinCURRENCYValue) as NetWin,
from dbo.dimPlayer as P
    inner join dbo.factRevenue as R on P.playerKey = R.playerKey
    inner join dbo.vw_Date as dD on Dd.dateKey = R.dateKey
where P.CustomerID = 12345
group by dD.[Date]
order by dD.[Date]

;with cte as (
    select T.ID, T.[Date], T.NetWin, T.NetWin as CumulativeNetWin
    from #Temp as T
    where T.ID = 1

    union all

    select T.ID, T.[Date], T.NetWin, T.NetWin + C.CumulativeNetWin as CumulativeNetWin
from cte as C
    inner join #Temp as T on T.ID = C.ID + 1
)
select C.[Date], C.NetWin, C.CumulativeNetWin
from cte as C
order by C.[Date]

入力に重複する日付がある可能性があると仮定しますが、出力に重複したくないので、テーブルに入れる前にデータをグループ化しました。

于 2013-08-29T16:22:47.463 に答える