This is a type of gaps-and-islands problem. Fortunately, you can use the difference of row numbers:
select userid, counter1, count(*)
from (select t.*,
row_number() over (partition by userid order by counter2) as seqnum,
row_number() over (partition by userid, counter1 order by counter2) as seqnum_2
from t
) t
group by userid, counter1, (seqnum - seqnum_2)
order by userid, min(counter2);
Note: This assumes that the ordering is based on counter2
. If it is really based on date
then you can use that column instead.
Why this works is a little tricky to explain. But if you look at the results from the subquery, you will see how the difference between the two row_number()
values is constant when counter1
has the same value on adjacent rows.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…