sql - Efficient way to combine 2 tables and get the row with max year with preference to one of the table
问题描述
I am trying to combine 2 tables (key_ratios_cnd and key_ratios_snd) both tables are identical and primary key columns for both tables are symbol and fiscal_year.
In the final result set i want the row with maximum year in both the tables for each symbol. if the row with maximum year is present in both the tables then row from key_ratios_cnd should be selected.
I come up with below SQL query to give the result. I wanted to know if their are any other way to write the query that is more optimized.
select sq2.*
from
(select sq.*,
max(id) over(partition by sq.symbol) as max_id,
max(fiscal_year) over(partition by sq.symbol) as max_year
from
( select *,'2' as id
from test.key_ratios_cnd
union all
select *,'1' as id
from test.key_ratios_snd
) as sq
) as sq2
where id = max_id and fiscal_year = max_year
order by symbol asc
解决方案
我会先从每个表中选择一行,然后合并。Postgresdistinct on
非常适合这个目的。
select distinct on (symbol) sc.*
from ((select distinct on (cnd.symbol) cnd.*, 1 as ord
from test.key_ratios_cnd cnd
order by cnd.symbol, cnd.fiscal_year desc
) union all
(select distinct on (snd.symbol) cnd.*, 2 as ord
from test.key_ratios_cnd cnd
order by snd.symbol, snd.fiscal_year desc
)
) sc
order by symbol, fiscal_year desc, ord;
为了加快速度,(symbol, fiscal_year desc)
为每个表添加一个索引。
推荐阅读
- r - 如何用多行(变量)切换多列(年)?
- laravel - update() 函数使访问器在 laravel 中执行两次
- reactjs - 如果我使用扩展运算符,为什么状态会发生变化?
- javascript - 使用套接字和节点发送图像/视频
- reactjs - 如何在数据地图上获得正确的鼠标悬停坐标
- html - 如何覆盖多个 PNG 并让每个 PNG 在其可见区域中都可点击?
- java - 如果 Uid 列表已经在数据库 Firebase ( Android ) 中,请检查
- visual-studio - 如何使用原始解决方案从另一台计算机调试 minidump.mdmp?
- c# - 我需要在表中查询两个重复列中的值
- powershell - ForEach 循环与 CLI 中打印的不一样?