如何使用滞后获取特定时间 window 之前的前一行数据?
How do I use lag to get the previous row before a specific time window of data?
我每天都会创建一个如下所示的 table:
user_id
received_at
age_pref
ethnicity_pref
1
10:01
18-28
open_to_all
2
10:05
18-23
open_to_all
1
10:08
18-30
open_to_all
2
10:07
18-25
Hispanic/Iatino
3
10:09
56-33
White
这是一个 table,列出了用户从上午 10 点到 11 点执行的操作。如您所见,有 3 个不同的用户 ID。
使用此方法,我尝试使用 lag
创建另一个 table 以查看先前的值是否已更改。但是,问题是第一行不准确,因为我无法衡量属性是否在这组数据之前没有前一行的情况下发生了变化(可能发生在上午 930 点)。如何为这个 table 中的每个用户 ID 获取前一个 received_at
行,但每个 user_id 仅获取 1 个?我希望新的 table 看起来像这样,新记录放在开头
user_id
received_at
age_pref
ethnicity_pref
1
9:48
20-30
asian
2
9:52
30-32
white
3
9:58
28-30
open_to_all
1
10:01
18-28
open_to_all
2
10:05
18-23
open_to_all
1
10:08
18-30
open_to_all
2
10:07
18-25
Hispanic/Iatino
3
10:09
56-33
White
请注意,在此时间间隔之前存在多行。对于 table.
中存在的 user_id,我希望在 table 前面加上最近的一个
基本上我想在时间 window 之前为每个 user_id 添加 1 行,这样我跟踪变化的 table 是准确的,因为滞后总是让第一行为空。
我猜你可以union all
以下查询:
select distinct on (user_id) user_id, received_at, age_pref, ethnicity_pref
from t
order by user_id, received_at desc
where received_at < '10:00'
我每天都会创建一个如下所示的 table:
user_id | received_at | age_pref | ethnicity_pref |
---|---|---|---|
1 | 10:01 | 18-28 | open_to_all |
2 | 10:05 | 18-23 | open_to_all |
1 | 10:08 | 18-30 | open_to_all |
2 | 10:07 | 18-25 | Hispanic/Iatino |
3 | 10:09 | 56-33 | White |
这是一个 table,列出了用户从上午 10 点到 11 点执行的操作。如您所见,有 3 个不同的用户 ID。
使用此方法,我尝试使用 lag
创建另一个 table 以查看先前的值是否已更改。但是,问题是第一行不准确,因为我无法衡量属性是否在这组数据之前没有前一行的情况下发生了变化(可能发生在上午 930 点)。如何为这个 table 中的每个用户 ID 获取前一个 received_at
行,但每个 user_id 仅获取 1 个?我希望新的 table 看起来像这样,新记录放在开头
user_id | received_at | age_pref | ethnicity_pref |
---|---|---|---|
1 | 9:48 | 20-30 | asian |
2 | 9:52 | 30-32 | white |
3 | 9:58 | 28-30 | open_to_all |
1 | 10:01 | 18-28 | open_to_all |
2 | 10:05 | 18-23 | open_to_all |
1 | 10:08 | 18-30 | open_to_all |
2 | 10:07 | 18-25 | Hispanic/Iatino |
3 | 10:09 | 56-33 | White |
请注意,在此时间间隔之前存在多行。对于 table.
中存在的 user_id,我希望在 table 前面加上最近的一个基本上我想在时间 window 之前为每个 user_id 添加 1 行,这样我跟踪变化的 table 是准确的,因为滞后总是让第一行为空。
我猜你可以union all
以下查询:
select distinct on (user_id) user_id, received_at, age_pref, ethnicity_pref
from t
order by user_id, received_at desc
where received_at < '10:00'