使用零值填充临时表

时间:2015-12-29 13:16:28

标签: sql sql-server

我有一张桌子#results,我在表格中填写了一些值,但是如果我没有匹配,那么在过去的8周内,它不会填满表格

这是我的插入和合并代码

INSERT INTO #Results (
            [PlayerId],
            [CalendarWeekID],
            [TotalDepositAmount],
            [TotalDepositCount],
            [TotalWithdrawalAmount],
            [TotalWithdrawalCount]
            )
        SELECT
            [PlayerId],
            [CalendarWeekID],
            SUM(Aggr.DepositAmount)     [Deposits],
            SUM(Aggr.DepositCount)      [DepositCount],
            SUM(Aggr.WithdrawalAmount)  [Withdrawals],                      
            SUM(Aggr.WithdrawalCount)   [WithdrawalCount]
       FROM [WarehouseMgmt].[FactPaymentAgr] Aggr
       JOIN WarehouseMgmt.DimTime DT on DT.Id = Aggr.TimeId
       WHERE (CalendarWeekId BETWEEN @CurrentWeek7 AND @CurrentWeek) AND [PlayerId] = @PlayerID
       GROUP BY [PlayerId],[CalendarWeekID]

    MERGE #Results AS Target
          USING(    SELECT 
                        [PlayerId],
                        [CalendarWeekID],
                        SUM(Aggr.FinancialBetAmount) [TotalBetAmount],
                        SUM(Aggr.FinancialBetCount)  [TotalBetCount]
                    FROM [WarehouseMgmt].[FactWalletAgr] Aggr
                    JOIN [WarehouseMgmt].[DimPlayer] DPL ON Aggr.[PlayerId] = DPL.[Id] 
                    JOIN WarehouseMgmt.DimTime DT on DT.Id = Aggr.TimeId
                    WHERE (CalendarWeekId BETWEEN @CurrentWeek7 AND @CurrentWeek) AND [PlayerId] = @PlayerID
                    GROUP BY [PlayerId],[CalendarWeekID]) AS Source
          ON (Target.[PlayerId] = Source.[PlayerId])
          WHEN MATCHED THEN
                UPDATE SET  Target.[TotalBetAmount] = Source.[TotalBetAmount],
                            Target.[TotalBetCount] = Source.[TotalBetCount] ; 

一名玩家的当前结果将采用此格式

PlayerId一些数量和数量CalendarWeekId CalendarWeek 1110,10,1,... 201553(周id) 1110,1000,23,... 201547(weekId)

但我想要的是表格中所有过去8周的数据,即使它是0 所以正确的格式将是

  1. 1110,10,1,... 201553(周ID)
  2. 1110,0,0,... 201552(周ID)
  3. 1110,0,0,... 201552(周ID)
  4. 1110,0,0,... 201551(周ID)
  5. 1110,0,0,... 201550(周ID)
  6. 1110,0,0,... 201549(周ID)
  7. 1110,0,0,... 201548(周ID)
  8. 1110,1000,23,... 201547(weekId)
  9. 缺少的行应为0

1 个答案:

答案 0 :(得分:0)

您只包含一位玩家的数据,因此您可以使用td解决此问题。 left join语句应如下所示:

insert