Du kan tildele en grupperingsparameter ved at tælle antallet af done
poster før hver post. Resten er kun sammenlægning, selvom det virker som en unødvendig komplikation at tildele et bogstav til hver gruppe:
select grp as record, min(Date) as DateBegin,
max(case when Action = 'Done' then Date end) as DateEnd,
count(*) as NumActions,
sum(case when Action = 'Escalation' then 1 else 0 end) as NumEscalations
from (select e.*, coalesce(e2.grp, 0) as grp
from example e outer apply
(select count(*) as grp
from example e2
where e2.id < e.id and e2.Action = 'Done'
) e2
) e
group by grp;
Denne forespørgsel ville være enklere (og mere effektiv) i SQL Server 2012+, som understøtter kumulative summer.
EDIT:
Jeg bemærker, at jeg bruger en underforespørgsel til dette, men det er ikke nødvendigt. Dette kan skrives som:
select coalesce(grp, 0) as record, min(Date) as DateBegin,
max(case when Action = 'Done' then Date end) as DateEnd,
count(*) as NumActions,
sum(case when Action = 'Escalation' then 1 else 0 end) as NumEscalations
from example e outer apply
(select count(*) as grp
from example e2
where e2.id < e.id and e2.Action = 'Done'
) e2
group by e2.grp