查找一列中包含 6 个连续 1 的组
我有一个包含 2 列的表:
val
其值:0 或 1id
具有唯一标识符
with cte(val, id) as (
select 0, 0 union all
select 1, 1 union all
select 1, 2 union all
select 0, 3 union all
select 1, 4 union all
select 1, 5 union all
select 1, 6 union all
select 1, 7 union all
select 1, 8 union all
select 1, 9 union all
select 1, 10
)
select *
into #tmp
from cte
如何查找连续 6 个值 = 1 的 id。
在上面的示例中:id = 9,id = 10。
最好不要使用循环(游标或 while),而是使用类似于 sum(...) over(...)
的内容。
I have a table with 2 columns:
val
with values: 0 or 1id
with unique identifiers
with cte(val, id) as (
select 0, 0 union all
select 1, 1 union all
select 1, 2 union all
select 0, 3 union all
select 1, 4 union all
select 1, 5 union all
select 1, 6 union all
select 1, 7 union all
select 1, 8 union all
select 1, 9 union all
select 1, 10
)
select *
into #tmp
from cte
How do I to find id with 6 values = 1 in a row.
In the example above: id = 9, id = 10.
It is desirable not to use loops (cursors or while), but something like sum(...) over(...)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不
LAG()
(但你需要一个订单列):Why not
LAG()
(but you need an order column):您可以在包含 6 行(前 5 行加当前行)的窗口框架上使用运行求和:
调整窗口和 where 子句的大小以匹配所需的值。
You can use running sum over a window frame that contains exactly 6 rows (5 prior plus current row):
Adjust the size of the window and where clause to match the desired value.
另一种方法是在 LAG 值上使用 ROW_NUMBER,
结果是
亲自尝试 在此 DBFiddle
这种方法的优点是您可以轻松地设置值6 到任何其他值
编辑
正如@Zhorov 在评论中提到的,我的代码中有一个缺陷,当您添加某些行时它会返回错误的结果
此解决方案将修复该问题,它基于@SalmanA 的解决方案,因此接受答案的功劳应该归于他
,并且再次 DBFiddle
Another approach is using ROW_NUMBER on the LAG values
the result is
Try it yourself in this DBFiddle
The advantage of this method is that you can easy set the value from 6 to any other value
EDIT
As @Zhorov mentioned in the comment, there is a flaw in my code, it returns the wrong results when you add certain rows
This solution will fix that, it is based on the solution of @SalmanA so the credit for accepted answer should go to him
And again a DBFiddle