【问题标题】:Redshift - Max window function with ConditionRedshift - 带条件的最大窗口函数
【发布时间】:2020-09-25 04:49:21
【问题描述】:

我正在尝试获取特定字段在过去 3 个月、过去 6 个月和自成立以来相对于特定日期并按 part_id 分区的最大值。

对于自成立以来的最大值,我使用了以下查询。

select 
 part_id,
 date_field,
 MAX(val) OVER(partition by part_id order by date_field rows unbounded preceding) as max_since_inception
FROM my_table;

如何添加条件以仅在我的 date_field 的最后 3 个月内获得最大值?

例如。如果 date_field 是 2020-09-25, max_l3m 必须在 2020-06-25 和 2020-09-25 之间具有最大值; max_l6m 必须在 2020-03-25 和 2020-09-25 之间具有最大值; max_since_inception 自成立到 2020-09-25 必须具有 max_value 并按 part_id 分区

【问题讨论】:

  • 提供一些样本数据和你想要的输出
  • @Fahmi 我已将所需的输出与示例数据一起放入

标签: sql amazon-redshift window-functions


【解决方案1】:

Redshift 不支持窗口框架,因此您只能使用自联接或其他一些复杂的构造:

select t.part_id, t.date_field,
       max(case when tprev.date_field > t.date_field - interval '3 month' then value end) as max_l3m,
       max(case when tprev.date_field > t.date_field - interval '6 month' then value end) as max_l6m
from t join
     t tprev
     on tprev.part_id = t.part_id and tprev.date_field <= t.date_field;

您可能还希望将回溯期限制为 6 个月,如果这是您真正需要的最长时间范围。

【讨论】:

  • 这似乎随着我拥有的数据大小而导致红移崩溃。我正在使用单个节点运行。
猜你喜欢
  • 2017-08-14
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多