因此,我有一个名为"reports“的表,其组织形式如下:
id | stock_id | type | time_period | report_date
类型可以是"Cash_Flow“、"Income_Statement”或"Balance_Sheet",time_period可以是“季度”或“每年”,report_date是日期。我想要做的实际上是只获取每个stock_id的最新报告(按report_date排序)。
因此,如果一只股票同时有"Cash_Flow“、"Income_Statement”和"Balance_Sheet“季度报告,2019-04-30和2019-01-30以及2019-04-30的年度报告,我只想获得每只股票的最新季度报告,而不返回任何年度报告或任何较早的报告。因此,假设有100只股票,表中每种报告类型总共有8个季度(季度报告共2400行),每种类型有2个年度报告(600行年度报告)。
所以我现在在Ubuntu 18.04上运行PostgreSQL10.8。我通常不会编写原始sql (通常使用ORM),所以如果答案真的很简单,我很抱歉。
因此,我尝试对每个报告执行以下操作,但它会返回所有行(不出所料),而我只需要最新的行。我认为解决方案可能需要一个截然不同的,但我不能看起来与orderby一起工作。
SELECT *
FROM public.reports where time_period='quarterly' and type='Cash_Flow' group by id, stock_id order by report_date desc;
我希望select查询只返回300行,只包含100只股票中每只股票的最新3个(Income_Statement,Balance_Sheet,Cash_Flow)报告,或者如果对这3种报告类型中的每种类型进行3次查询更容易,则每种类型都返回100行。
发布于 2019-05-28 18:46:19
我想要一个select查询,它只返回300行,只包含100只股票中每只股票的最新3个报告。
使用窗口函数。假设你有100只股票:
select r.*
from (select r.*,
row_number() over (partition by stock_id, type order by report_date desc) as seqnum
from public.reports r
where time_period = 'quarterly' and
type in ( 'Cash_Flow', 'Income_Statement', 'Balance_Sheet' )
) r
where seqnum = 1;
https://stackoverflow.com/questions/56340336
复制相似问题