我认为您需要LAG功能。最简单的情况是这样的:
[Home1] = LAG(result_Home, 1) OVER(PARTITION BY [Home(no.)] ORDER BY ID),
但是,它并不像这样简单,因为您需要引用 home 或 away,因此您需要首先取消透视数据
SELECT ID,
Type,
TeamID,
Result
FROM T
CROSS APPLY
( VALUES
('Home', [Home(no.)], Result_Home),
('Away', [Away(no.)], Result_Away)
) Upvt (Type, TeamID, Result);
这意味着您可以在一个列中访问每个团队的结果,无论是主场还是客场(对于滞后功能)。
然后使用这个未透视的数据,您应用滞后来获得前 4 个结果(我使用过ORDER BY ID
,但我假设我缺少一个日期字段?):
SELECT *,
[Result1] = LAG(Result, 1) OVER(PARTITION BY TeamID ORDER BY ID),
[Result2] = LAG(Result, 2) OVER(PARTITION BY TeamID ORDER BY ID),
[Result3] = LAG(Result, 3) OVER(PARTITION BY TeamID ORDER BY ID),
[Result4] = LAG(Result, 4) OVER(PARTITION BY TeamID ORDER BY ID)
FROM (Previous Query)
然后,一旦您获得了每支球队每场比赛的前 4 个结果,您就可以将未透视的数据重新组合在一起,以使主队和客队再次位于同一行,从而提供完整的查询:
WITH Results AS
( SELECT ID,
Type,
TeamID,
Result
FROM T
CROSS APPLY
( VALUES
('Home', [Home(no.)], Result_Home),
('Away', [Away(no.)], Result_Away)
) Upvt (Type, TeamID, Result)
), Results2 AS
( SELECT *,
[Result1] = LAG(Result, 1) OVER(PARTITION BY TeamID ORDER BY ID),
[Result2] = LAG(Result, 2) OVER(PARTITION BY TeamID ORDER BY ID),
[Result3] = LAG(Result, 3) OVER(PARTITION BY TeamID ORDER BY ID),
[Result4] = LAG(Result, 4) OVER(PARTITION BY TeamID ORDER BY ID)
FROM Results
)
SELECT Home.ID,
[Home(no.)] = Home.TeamID ,
[Away(no.)] = Away.TeamID,
[Result_Home] = Home.Result,
[Result_Away] = Away.Result,
[Home1] = Home.Result1,
[Home2] = Home.Result2,
[Home3] = Home.Result3,
[Home4] = Home.Result4,
[Away1] = Away.Result1,
[Away2] = Away.Result2,
[Away3] = Away.Result3,
[Away4] = Away.Result4
FROM Results2 AS Home
INNER JOIN results2 AS Away
ON Away.ID = Home.ID
AND Away.Type = 'Away'
WHERE Home.Type = 'Home'
ORDER BY ID;
SQL Fiddle 示例