I want to count some certain values until a specific event occurred in SQL. This is very similar question to this question:
The answer to this question didn't solve my problem which I am confused with RANGE BETWEEN 1 PRECEDING AND 1 PRECEDING too. Differently from that question I don't look for strings but I want to count other events.
My table would be like
User Event Day
1 C 2019-01-10
1 B 2019-01-11
1 D 2019-01-12
1 A 2019-01-13
2 D 2019-01-10
2 B 2019-01-11
2 C 2019-01-12
2 D 2019-01-13
2 A 2019-01-14
2 E 2019-01-15
I would like to count C or D until event A or B occured.
I try
COUNTIF(Event = 'C' OR Event = 'D') OVER(PARTITION BY User ORDER BY Day ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS count_events
But this doesn't stop counting until event A or B. It counts all C or D events in partition.
My result table would look like this and the counting would stop if one of the event is occurred and restart counting again when the expected event occurs.
User Event Day count_events
1 C 2019-01-10 0
1 B 2019-01-11 1
1 D 2019-01-12 0
1 A 2019-01-13 1
2 D 2019-01-10 0
2 B 2019-01-11 1
2 C 2019-01-12 0
2 D 2019-01-13 1
2 A 2019-01-14 2
2 E 2019-01-15 0