pat*_*rit 5 sql postgresql window-functions
假设我有下表:
CREATE TABLE stock_prices (
stock TEXT NOT NULL,
date DATE NOT NULL,
price REAL NOT NULL,
UNIQUE (stock, date)
);
Run Code Online (Sandbox Code Playgroud)
我想计算每一天,前3个月窗口中每只股票的最高价格.
我不能做一个简单的自我加入,date - INTERVAL(3 'MONTH')
因为我的stock_price
桌子有假期和周末的一些"漏洞".同样,一个天真的窗口也不起作用:
SELECT
stock,
date,
LAST_VALUE(price) OVER (PARTITION BY stock ORDER BY date ROWS 90 PRECEDING)
FROM stock_prices
Run Code Online (Sandbox Code Playgroud)
我几乎想要一个窗框,这里有一个基于当前行的条件.这可能在PostgreSQL中吗?
您可以使用该函数填充缺少行的表generate_series ()
,因此窗口函数将返回正确的数据.您可以选择指定开始日期和结束日期的报告周期generate_series ()
:
select
stock,
date,
price,
max(price) over (partition by stock order by date rows 90 preceding)
from (
select d::date as date, s.stock, sp.price
from generate_series('2016-01-01'::date, '2016-07-28', '1d') g(d)
cross join (
select distinct stock
from stock_prices
) s
left join stock_prices sp on g.d = sp.date and s.stock = sp.stock
) s
order by 1, 2;
Run Code Online (Sandbox Code Playgroud)
这个替代解决方案带有一个简单的子查询:
select
stock,
date,
price,
(
select max(price)
from stock_prices sp2
where sp2.stock = sp1.stock
and sp2.date >= sp1.date- interval '90days'
and sp2.date <= sp1.date
) highest_price
from
stock_prices sp1
order by 1, 2;
Run Code Online (Sandbox Code Playgroud)
会贵得多.在这种情况下,您应该强制使用索引
create index on stock_prices (stock, date);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
769 次 |
最近记录: |