我正在尝试计算相对日期范围内的值的最大值。假设我有这些列:日期,周,类别,价值。注意:“周”列是相应日期的星期一。
我想生成一个表格,在每个日期,星期,类别组合的最后两周内给出MAX值,以便输出产生以下内容:Date,Week,Category,Value,2WeeksPriorMAX。
我将如何编写该查询?我认为以下方法不起作用:
SELECT Date, Week, Value,
MAX(Value) OVER (PARTITION BY Category
ORDER BY Week
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) as 2WeeksPriorMAX
上述查询未考虑过去2周内给定类别,周组合缺失值的情况,因此在分析前两行时,它将超过2周。
答案 0 :(得分:1)
左连接或使用横向连接/子查询可能很昂贵。您可以使用窗口函数执行此操作,但您需要更多逻辑:
select t.*,
(case when lag(date, 1) over (partition by category order by date) < date - interval '2 week'
then value
when lag(date, 2) over (partition by category order by date) < date - interval '2 week'
then max(value) over (partition by category order by date rows between 1 preceding and current row)
else max(value) over (partition by category order by date rows between 2 preceding and current row)
end) as TwoWeekMax
from t;