[英]SQL query to partition rows into groups where lag (difference between rows) is greater than some value
假設我有一張像
ID |
---|
1 |
3 |
4 |
10 |
12 |
19 |
如果它們相差 5 或更少,我想將 id (按排序順序)分組到同一組,如果它們相差 6 或更多,我想將它們分組到一個新組中。 所以 output 將是:
ID | 團體 |
---|---|
1 | 1 |
3 | 1 |
4 | 1 |
10 | 2 |
12 | 2 |
19 | 3 |
這在 SQL 中是否可行? 這將是 Trino 中的一個查詢,我看到他們有諸如lag
和partition
之類的命令。 有沒有人提出這樣的查詢可以提供幫助?
您可以將cte
與lead
一起使用:
with cte(id, l1) as (
select t.id, abs(coalesce(lead(t.id) over (order by t.id), 0) - t.id) < 6 from tbl t
)
select c.id, (select sum(c1.id < c.id and c1.l1 = 0) from cte c1) + 1 from cte c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.