我想计算具有完全相同结构的两个表的行之间的增量,但不一定是相同的数据。
表1(预测)
Id |名称| GP | G |甲
表1(实际数据)
Id |名称| GP | G |甲
结果(与Id匹配):
Id | (GP1-GP2)AS DeltaGP | (G1-G2)AS DeltaG | (A1-A2)AS DeltaA |
抓住我的漂移?这是为了解决SSAS中预测模型的错误
这是我的代码:
SELECT P.[Player_id]
,P.[PlayerName]
,sum(P.[Games Played])-sum(S.[GamesPlayed]) AS GP
,sum(P.[Total Goals])-sum(s.[TotalGoals]) AS Goals
,sum(P.[Total Assists])-sum(s.[TotalAssists]) AS Assists
FROM [PredictionsPlayersHistory] as P
JOIN [V_StatsPlayers] AS S on p.pLAYER_id = s.Player_id
where S.LastPlayedDate >= '2010-02-01' and P.Player_id
= 8471675 group by P.[Player_id],P.[PlayerName]
order by Goals desc, Assists desc, GP asc
问题是结果不对:
预测(SUM)
PlayerName GP目标助攻
Sidney Crosby 56 28 34
实际数据(SUM)
PlayerName GP目标助攻
Sidney Crosby 26 17 24
结果
Sidney Crosby 28 -42 -98
答案 0 :(得分:0)
你可以通过ID加入桌子吗?如果我做对了,那么:
SELECT table1.id, table1.name,
(table1.gp - table2.gp) as DeltaGP,
(table1.g - table2.g) as DeltaG,
(table1.a - table2.a) as DeltaA
FROM table1
JOIN table2
ON table1.id = table2.id
答案 1 :(得分:0)
您需要加入id列上的两个表:
SELECT a.Id,a.Name, a.GP - p.GP AS DeltaGP, a.G - p.G AS DeltaG, a.A - p.A AS DeltaA
FROM dbo.table1 AS a --actual values
JOIN dbo.table2 AS p --predictions
ON a.Id = p.Id;
有关SQL Server联接的介绍,请查看我的帖子系列:http://sqlity.net/en/1146/a-join-a-day-introduction/
编辑:如果每个表中每个玩家有多行,则需要在加入之前聚合它们:
SELECT a.Id,
a.Name,
a.GP - p.GP AS DeltaGP,
a.G - p.G AS DeltaG,
a.A - p.A AS DeltaA
FROM (
SELECT Id,
Name,
SUM(GP) AS GP,
SUM(G) AS G,
SUM(A) AS A
FROM dbo.table1
GROUP BY Id,
Name
) AS a --actual values
JOIN (
SELECT Id,
SUM(GP) AS GP,
SUM(G) AS G,
SUM(A) AS A
FROM dbo.table2
GROUP BY Id
) AS p
--predictions
ON a.Id = p.Id;
根据您的要求,您可能希望使用AVG而不是SUM。