如何使用 lead/lag 获取 SQL 中最后 n 个值的总和
How do I get the aggregate of last n values in SQL using lead/lag
我正在考虑聚合三行中的最后一行(即尝试在最后三行中尝试列的最大值)。有没有办法我们可以一起使用 LAG 和 MAX。我能够通过创建一个函数并使用它来实现,但效率不高。有什么更好的方法。
select symbol, td_timestamp, open, vol_range, fn_getmaxvalue(high, hihi, hihi2) as highest
from
(select symbol, td_timestamp, open, high, low,
volume-lag(volume,2) over (partition by symbol order by td_timestamp ) vol_chg,
lag(high,1) over (partition by symbol order by td_timestamp ) hihi,
lag(high,2) over (partition by symbol order by td_timestamp ) hihi2
from tb_nfbnf where trade_date='2020-02-28' and processed_flg is null
order by symbol, td_timestamp)a
如果我没理解错的话,你想要 运行 最大值。这将在 window 函数中使用 window 框架子句:
select t.*,
max(high) over (partition by symbol
order by td_timestamp
rows between 2 preceding and current row
) as max_hi_3rows
from tb_nfbnf t
where trade_date = '2020-02-28' and processed_flg is null
order by symbol, td_timestamp;
** 从之前的 2 行更改为之前的 2 行 **
我正在考虑聚合三行中的最后一行(即尝试在最后三行中尝试列的最大值)。有没有办法我们可以一起使用 LAG 和 MAX。我能够通过创建一个函数并使用它来实现,但效率不高。有什么更好的方法。
select symbol, td_timestamp, open, vol_range, fn_getmaxvalue(high, hihi, hihi2) as highest
from
(select symbol, td_timestamp, open, high, low,
volume-lag(volume,2) over (partition by symbol order by td_timestamp ) vol_chg,
lag(high,1) over (partition by symbol order by td_timestamp ) hihi,
lag(high,2) over (partition by symbol order by td_timestamp ) hihi2
from tb_nfbnf where trade_date='2020-02-28' and processed_flg is null
order by symbol, td_timestamp)a
如果我没理解错的话,你想要 运行 最大值。这将在 window 函数中使用 window 框架子句:
select t.*,
max(high) over (partition by symbol
order by td_timestamp
rows between 2 preceding and current row
) as max_hi_3rows
from tb_nfbnf t
where trade_date = '2020-02-28' and processed_flg is null
order by symbol, td_timestamp;
** 从之前的 2 行更改为之前的 2 行 **