我認爲你需要LAG函數。最簡單的情況會是這樣的:
[Home1] = LAG(result_Home, 1) OVER(PARTITION BY [Home(no.)] ORDER BY ID),
但是,它並不像這樣簡單,因爲你需要引用在家或外出,所以你需要先逆透視數據
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;
Example on SQL Fiddle
哇!這很好。非常感謝!! –