Since you are on SQL Server 2012 you can use a couple of the new windowing functions.
with C1 as
(
select T.team_id,
case
when M.winning_team_id is null then 'T'
when M.winning_team_id = T.team_id then 'W'
else 'L'
end as streak_type,
M.match_id
from FantasyMatches as M
cross apply (values(M.home_fantasy_team_id),
(M.away_fantasy_team_id)) as T(team_id)
), C2 as
(
select C1.team_id,
C1.streak_type,
C1.match_id,
lag(C1.streak_type, 1, C1.streak_type)
over(partition by C1.team_id
order by C1.match_id desc) as lag_streak_type
from C1
), C3 as
(
select C2.team_id,
C2.streak_type,
sum(case when C2.lag_streak_type = C2.streak_type then 0 else 1 end)
over(partition by C2.team_id
order by C2.match_id desc rows unbounded preceding) as streak_sum
from C2
)
select C3.team_id,
C3.streak_type,
count(*) as streak_count
from C3
where C3.streak_sum = 0
group by C3.team_id,
C3.streak_type
order by C3.team_id;
C1
calculates the streak_type
for each team and match.
C2
finds the previous streak_type
ordered by match_id desc
.
C3
generates a running sum streak_sum
ordered by match_id desc
keeping a 0
a long as the streak_type
is the same as the last value.
Main query sums up the streaks where streak_sum
is 0
.