Sql 用零值填充临时表
我有一个表#结果,我用一些值填充该表,但如果我没有匹配项,则在过去8周内直到最后一周才会填充该表 这是我的插入和合并代码Sql 用零值填充临时表,sql,sql-server,Sql,Sql Server,我有一个表#结果,我用一些值填充该表,但如果我没有匹配项,则在过去8周内直到最后一周才会填充该表 这是我的插入和合并代码 INSERT INTO #Results ( [PlayerId], [CalendarWeekID], [TotalDepositAmount], [TotalDepositCount], [TotalWithdrawalAmount],
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)
11101000,23,…201547(周末)
但我想要的是表中所有过去8周的数据,即使是0
因此,正确的格式将是
缺少的行应为0您只包含一名玩家的数据,因此可以使用
左连接解决此问题。insert
语句应该如下所示:
INSERT INTO #Results ( . . . )
SELECT . . .
FROM WarehouseMgmt.DimTime DT LEFT JOIN
WarehouseMgmt.FactPaymentAgr Aggr
ON DT.Id = Aggr.TimeId AND [PlayerId] = @PlayerID
WHERE (CalendarWeekId BETWEEN @CurrentWeek7 AND @CurrentWeek)
GROUP BY PlayerId, CalendarWeekID
您只包含一名玩家的数据,因此可以使用左连接解决此问题。insert
语句应该如下所示:
INSERT INTO #Results ( . . . )
SELECT . . .
FROM WarehouseMgmt.DimTime DT LEFT JOIN
WarehouseMgmt.FactPaymentAgr Aggr
ON DT.Id = Aggr.TimeId AND [PlayerId] = @PlayerID
WHERE (CalendarWeekId BETWEEN @CurrentWeek7 AND @CurrentWeek)
GROUP BY PlayerId, CalendarWeekID
好的,我重新安排了查询,但有一个问题,不能在PlayerId中插入空值。答案是开始。您还需要为每个要默认为零的字段提供一个isnull()函数。@user2171512。创建临时表时,为数字列指定默认值零。这可能是最简单的解决方案。好的,我重新安排了查询,但有一个问题,不能在PlayerId中插入空值。这个答案是一个开始。您还需要为每个要默认为零的字段提供一个isnull()函数。@user2171512。创建临时表时,为数字列指定默认值零。这可能是最简单的解决办法。