我正在尝试编写一个sql查询(在亚马逊红移中),该查询计算客户从不符合条件到满足条件的次数,因此当1出现0之后的日期时。
我正在努力找出执行此操作的逻辑
ID Snapshot_date Meets Criteria
55 1/1/2018 0
55 1/5/2018 1
55 1/10/2018 1
55 1/15/2018 1
55 1/20/2018 0
55 1/25/2018 1
答案 0 :(得分:0)
使用lag
获取上一个值,检查条件并count
。
select id,count(*)
from (select id,snapshot_date
,lag(meets_critetria,1) over(partition by id order by snapshot_date) as prev_m_c
from tbl
) t
where prev_m_c = 0 and meets_criteria = 1
group by id