我正在尝试从网络表中查找某人访问过的先前页面。我使用滞后函数来查找该人访问过的先前页面(仅当访问了下一页时)。
网络表:
id | 访问时间 | 网页_访问过 |
---|---|---|
1 | 2024-03-14 10:00:01 | google.com |
1 | 2024-03-14 10:00:07 | |
1 | 2024-03-14 10:01:15 | |
1 | 2024-03-14 10:01:10 | espn.com |
1 | 2024-03-14 10:02:01 |
当我使用下面的 SQL 时,返回的值不考虑行之间的空/空白值。
使用的SQL:
select id,
visit_time,
webpage_visited,
coalesce(lag(webpage_visited, 1) over (partition by id order by visit_time asc), 'none') as previous_webpage_visited
from web
请告知我如何实现以下预期输出。
预期输出:
id | 访问时间 | 网页_访问过 | 上一个_网页_访问过 |
---|---|---|---|
1 | 2024-03-14 10:00:01 | google.com | 无 |
1 | 2024-03-14 10:00:07 | ||
1 | 2024-03-14 10:01:15 | ||
1 | 2024-03-14 10:01:10 | espn.com | google.com |
1 | 2024-03-14 10:02:01 |
IGNORE NULLS
作为您的窗口函数并仅在当前值不为空时应用窗口函数:
sample data
WITH dataset(id, visit_time, webpage_visited) AS (
values (1,'2024-03-14 10:00:01','google.com'),
(1,'2024-03-14 10:00:07',NULL),
(1,'2024-03-14 10:01:15',NULL),
(1,'2024-03-14 10:01:10','espn.com'),
(1,'2024-03-14 10:02:01',NULL)
)
-- query
select id,
visit_time,
webpage_visited,
if(webpage_visited is not null,
coalesce(lag(webpage_visited, 1) IGNORE NULLS over(partition by id order by visit_time), 'none'))
as previous_webpage_visited
from dataset;
输出:
id | 访问时间 | 网页_访问过 | 上一个_网页_访问过 |
---|---|---|---|
1 | 2024-03-14 10:00:01 | google.com | 无 |
1 | 2024-03-14 10:00:07 | 空 | 空 |
1 | 2024-03-14 10:01:10 | espn.com | google.com |
1 | 2024-03-14 10:01:15 | 空 | 空 |
1 | 2024-03-14 10:02:01 | 空 | 空 |