您需要将deal
和security
表连接在一起。除了字段条件外security
,您还具有日期条件。
最后,您需要在该日期或之前找到最后一笔交易。大多数数据库都支持此row_number()
功能。
以下查询将这些组合在一起:
select scheme, security, asset_type, tran_type
from (select d.scheme, d.security, d.asset_type, d.tran_type,
row_number() over (partition by d.security order by d.value_date desc) as seqnum
from deal d join
schnav s
on d.security = s.security and
d.value_date <= s.nav_date and
s.nav_date = '31 Mar 2013'
) d
where seqnum = 1;
编辑:
要仅获取一个tran_type
,请在子查询中使用where
子句:
select scheme, security, asset_type, tran_type
from (select d.scheme, d.security, d.asset_type, d.tran_type,
row_number() over (partition by d.security order by d.value_date desc) as seqnum
from deal d join
schnav s
on d.security = s.security and
d.value_date <= s.nav_date and
s.nav_date = '31 Mar 2013'
where d.tran_type = 'P'
) d
where seqnum = 1;