如何根据一行的条件检索历史数据?

How to retrieve historical data based on condition on one row?

我有一个tablehistorical_data

ID Date column_a column_b
1 2011-10-01 a a1
1 2011-11-01 w w1
1 2011-09-01 a a1
2 2011-01-12 q q1
2 2011-02-01 d d1
3 2011-11-01 s s1

我需要根据与该 ID 相关的任意 1 行的日期条件检索该 ID 的整个历史记录。

date>='2011-11-01' 应该得到我

ID Date column_a column_b
1 2011-10-01 a a1
1 2011-11-01 w w1
1 2011-09-01 a a1
3 2011-11-01 s s1

我知道您可以通过使用 CTE 或像

这样的子查询来获得它
with selected_id as (
select id from historical_data where date>='2011-11-01' 
)
select hd.* from historical_data hd 
inner join selected_id si on hd.id = si.id

select * from historical_data 
where id in (select id from historical_data where date>='2011-11-01')

在这两种方法中,我都必须 query/scan table ``historical_data``` 两次。 我在 id 和日期上都有索引,所以 现在不是问题 ,但随着 table 的增长,这可能会导致问题。

上面的 table 是一个示例 table,我的 table 大小将达到 1TB,行数超过 600M。

有什么方法可以只查询一次 table 来实现吗? (我正在使用雪花)

使用QUALIFY:

SELECT *
FROM historical_data
QUALIFY MAX(date) OVER(PARTITION BY id) >= '2011-11-01'::DATE;