Я чувствую, что это возможно немного сложнее, однако, вот как я получил результат в итоге:
USE Sandbox;
GO
CREATE TABLE Game (GameTime time,
Team varchar(5),
Result varchar(4));
INSERT INTO Game
VALUES('05:00','Red','Win'),
('05:30','Red','Loss'),
('06:00','Red','Loss'),
('06:30','Red','Loss'),
('07:00','Red','Loss'),
('07:30','Red','Win'),
('08:00','Red','Win');
GO
WITH Grps AS(
SELECT GameTime,
Team,
Result,
LAG(Result,1,'Win') OVER (PARTITION BY Team ORDER BY GameTime) AS LastResult,
ROW_NUMBER() OVER (PARTITION BY Team ORDER BY GameTime) -
ROW_NUMBER() OVER (PARTITION BY Team, Result ORDER BY GameTime) AS Grp
FROM Game),
Counts AS (
SELECT GameTime,
Team,
Result,
LastResult,
COUNT(Team) OVER (PARTITION BY Team, Grp) AS GrpCount
FROM Grps)
SELECT GameTime,
Team,
Result,
CASE Result WHEN 'Loss' THEN 0
WHEN LastResult THEN 1
ELSE LAG(GrpCount,1,1) OVER (PARTITION BY Team ORDER BY GameTime)+1 END AS ToWin
FROM Counts;
GO
DROP TABLE Game;