[英]Partition & consecutive in SQL
堆垛机同行
我有一个像这样的数据集:
+---------+------+--------+
| user_id | date | metric |
+---------+------+--------+
| 1 | 1 | 1 |
| 1 | 2 | 1 |
| 1 | 3 | 1 |
| 2 | 1 | 1 |
| 2 | 2 | 1 |
| 2 | 3 | 0 |
| 2 | 4 | 1 |
+---------+------+--------+
我希望标记那些在指标列中连续 3 个“1”的客户。 我有如下解决方案。
select distinct user_id
from (
select user_id
,metric +
ifnull( lag(metric, 1) OVER (PARTITION BY user_id ORDER BY date), 0 ) +
ifnull( lag(metric, 2) OVER (PARTITION BY user_id ORDER BY date), 0 )
as consecutive_3
from df
) b
where consecutive_3 = 3
虽然它有效,但它不可扩展。 可以想象,如果我正在寻找连续的 50,上面的查询会是什么样子。请问是否有可扩展的解决方案? 任何云 SQL 都可以。 谢谢你。
如果你只想要这样的用户,你可以使用sum()
。 假设metric
仅为0
或1
:
select user_id,
(case when max(metric_3) = 3 then 1 else 0 end) as flag_3
from (select df.*,
sum(metric) over (partition by user_id
order by date
rows between 2 preceding and current row
) as metric_3
from df
) df
group by user_id;
通过使用窗口子句,您可以轻松扩展到任意数量的相邻1
s。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.