SQL 查找以下会话 - 不同于交叉连接的逻辑

SQL Find following session - different logic than cross join

我有一组数据存储两种类型的会话。这是移动数据使用量与 wifi 数据使用量的对比。

ID  Session_Type
1  Cell
2  WiFi
3  Cell
4  Cell
5  WiFi

.
.
.
.
1000 Cell
1001 WiFi

期望的结果

Cell_ID. Next_WiFi_sess_id
1        2
3        5
4        5 
.
.
1000    1001

我已经达到了自己加入 table 的程度,并且这样做的 id 大于 wifi id,但我确信这是否是完美的解决方案。你能在 Lag 中执行此操作以获得更好的性能吗?

select a.id, b.id
from 
table a
join table b
where a.id > min(b.id)

您可以使用 window 函数——具体来说,累积最小值:

select t.*
from (select t.*,
             min(case when session_type = 'WiFi' then id end) over (order by id rows between current row and unbounded following) as next_wifi_id
      from t
     ) t
where session_type = 'Cell';

这是一个使用 window 函数的选项:您可以在 window 分钟后获得下一个 WiFi 会话;诀窍是通过降序排列框架 id:

select id, next_wifi_id
from (
    select t.*,
        min(case when session_type = 'WiFi' then id end) over(order by id desc) next_wifi_id
    from mytable t
) t
where session_type = 'Cell'

Demo on DB Fiddle - 这是 Postgres,但行为在 Hive 中是相同的。

id | next_wifi_id
-: | -----------:
 1 |            2
 3 |            5
 4 |            5