Redshift sql 根据某个记录之前的时间戳识别记录
Redshift sql identify records based on timestamp which came before a certain record
我有一个红移 table 具有以下结构
titleId | country | updateTime | value
ID1 | US | 2020-01-01 00:00:00.000 | someValueA
ID1 | US | 2020-01-01 00:00:01.000 | someValueB
ID1 | IN | 2020-01-04 00:00:05.000 | someValue
ID2 ....
ID3....
ID1 | US | 2021-02-02 00:00:00.000 | someValue5
ID1 | GB | 2021-02-02 00:00:00.000 | someValue5
我试图找到 3 组,所有 titleIds [最好是整行,而不仅仅是 titleIds 列表],它们的国家 IN 在美国之后,
另一种方式是在 IN 之后有 US,所有标题只有 IN 条目,没有其他内容。
现在对于一个 titleId,我们可能有以下顺序 IN、US、IN、US,在这种情况下,我们在 IN 之后有 2 个 US 实例。
我最初想在同一个 table 上进行内部联接,这可以帮助我找到同时具有美国和印度领土的记录。但是后来我无法弄清楚如何使用这些结果来根据先于先出现的结果进行过滤。可以通过 Redshift SQL 实现吗?是否需要我在进行某种过滤后编写一些自定义代码?
您可以 select 满足条件的每一行使用:
select t.*
from (select t.*,
sum( (country = 'US')::int) over (partition by titleid order by updatetime rows between current row and unbounded following) as num_us_following,
sum( (country = 'IN')::int) over (partition by titleid order by updatetime rows between current row and unbounded following) as num_in_following,
sum( country <> 'IN')::int) over (partition by titleid) as non_nonind
from t
) t;
那么你的三个条件是:
where country = 'IN' and num_us_following > 0
where country = 'US' and num_in_following > 0
where country = 'IN' and non_nonin = 0
我有一个红移 table 具有以下结构
titleId | country | updateTime | value
ID1 | US | 2020-01-01 00:00:00.000 | someValueA
ID1 | US | 2020-01-01 00:00:01.000 | someValueB
ID1 | IN | 2020-01-04 00:00:05.000 | someValue
ID2 ....
ID3....
ID1 | US | 2021-02-02 00:00:00.000 | someValue5
ID1 | GB | 2021-02-02 00:00:00.000 | someValue5
我试图找到 3 组,所有 titleIds [最好是整行,而不仅仅是 titleIds 列表],它们的国家 IN 在美国之后, 另一种方式是在 IN 之后有 US,所有标题只有 IN 条目,没有其他内容。
现在对于一个 titleId,我们可能有以下顺序 IN、US、IN、US,在这种情况下,我们在 IN 之后有 2 个 US 实例。
我最初想在同一个 table 上进行内部联接,这可以帮助我找到同时具有美国和印度领土的记录。但是后来我无法弄清楚如何使用这些结果来根据先于先出现的结果进行过滤。可以通过 Redshift SQL 实现吗?是否需要我在进行某种过滤后编写一些自定义代码?
您可以 select 满足条件的每一行使用:
select t.*
from (select t.*,
sum( (country = 'US')::int) over (partition by titleid order by updatetime rows between current row and unbounded following) as num_us_following,
sum( (country = 'IN')::int) over (partition by titleid order by updatetime rows between current row and unbounded following) as num_in_following,
sum( country <> 'IN')::int) over (partition by titleid) as non_nonind
from t
) t;
那么你的三个条件是:
where country = 'IN' and num_us_following > 0
where country = 'US' and num_in_following > 0
where country = 'IN' and non_nonin = 0