[英]Get MAX Date while using SQL subquery with join
I have two tables Deal and SCHNAV with a common field 'security'. 我有两个表Deal和SCHNAV,它们具有共同的“安全性”字段。 Deal contains details of all securities purchased and sold till date and schnav contains closing security holding for each date.
交易包含截至日期为止所有已购买和出售的证券的详细信息,schnav包含每个日期的期末证券持有量。 I want an sql to fetch the latest (max) date for all trades done in securities held as on a particular date only upto that date from deal table.
我想让sql从交易表中获取直到特定日期为止的特定日期的所有证券交易的最新(最大)日期。
I used the following query to get all the deals and then from pivot got the latest value. 我使用以下查询获取所有交易,然后从数据透视表获取了最新的价值。 But i need an sql so that I dont have to do mnipulation in Excel.
但是我需要一个SQL,这样我就不必在Excel中进行模拟操作。
select scheme, security, asset_type, tran_type
from deal
where security in (select security from schnav where nav_date = '31 Mar 2013')
and d.value_date < '01 Apr 2013';
Please help. 请帮忙。 and Thanks in Advance
并预先感谢
You need to join the deal
and security
tables together. 您需要将
deal
表和security
表连接在一起。 In addition to the condition on the security
field, you also have conditions on the date. 除了
security
字段中的条件,您还具有日期条件。
Finally, you need to find the last deal on or before the date. 最后,您需要查找该日期或该日期之前的最后一笔交易。 Most databases support the
row_number()
function for this purpose. 为此,大多数数据库都支持
row_number()
函数。
The following query combines these together: 以下查询将这些结合在一起:
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;
EDIT: 编辑:
To get only one tran_type
, use a where
clause in the subquery: 要仅获取一个
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.