I think you need the LAG function. The simplest case would be something like:
[Home1] = LAG(result_Home, 1) OVER(PARTITION BY [Home(no.)] ORDER BY ID),
However, it is not quite as simple as this because you need to reference home or away, so you need to first unpivot your data
SELECT ID,
Type,
TeamID,
Result
FROM T
CROSS APPLY
( VALUES
('Home', [Home(no.)], Result_Home),
('Away', [Away(no.)], Result_Away)
) Upvt (Type, TeamID, Result);
This means you can access each teams result whether it is home or away all in one column (For the lag function).
Then with this unpivoted data you apply the lag to get the previous 4 results (I've used ORDER BY ID
but I'd assume there is a date field I am missing?):
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)
Then once you have each teams previous 4 results for each match you can join the unpivoted data back together to get the home and away teams on the same row again, giving the full query:
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