0

我想计算具有完全相同结构的两个表的行之间的增量,但不一定是相同的数据。

表 1(预测)

身份证 | 姓名 | 全科医生 | 克| 一种

表1(实际数据)

身份证 | 姓名 | 全科医生 | 克| 一种

结果(由 Id 匹配):

身份证 | (GP1-GP2) AS DeltaGP | (G1-G2) 作为 DeltaG | (A1-A2) 作为 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

问题是结果不对:

预测(总和)

PlayerName GP 进球助攻

西德尼·克罗斯比 56 28 34

实际数据 (SUM)

PlayerName GP 进球助攻

西德尼·克罗斯比 26 17 24

结果

西德尼·克罗斯比 28 -42 -98

4

2 回答 2

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
于 2012-12-14T20:52:19.770 回答
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 Joins 的介绍,请查看我的帖子系列: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。

于 2012-12-14T20:57:53.550 回答