我有两个表@tbl_numshr,其中包含每个证券或股票的股票数量以及包含的@tbl_shrprice 特定股票的每日价格。
我想知道每天的市场价值是nosshare * shrprice,但问题是,在表@tbl_numshr我没有每天的nosshare但是在 @tbl_shrprice我每天都有每个股票的入场券。
表@tbl_numshr包含由于某些公司对特定股票的操作而发生变化的数据,因此我想考虑旧数据,直到新日期的新数据无法使用。
请在这种情况下提供帮助。
declare @tbl_numshr table (id int identity ,sharecode int, nosshare float , logdate datetime )
declare @tbl_shrprice table(id int identity ,sharecode int , shrprice float, logdate datetime)
insert into @tbl_numshr (sharecode,nosshare,logdate)
values(1000, 1200.5,'2016-02-10'),(1000, 2100,'2016-02-17'),(1000, 2500,'2016-12-23')
insert into @tbl_shrprice (sharecode,shrprice,logdate)
values(1000, 10,'2016-01-01') , (1000, 12,'2016-01-02'),(1000, 18,'2016-01-03')
答案 0 :(得分:1)
使用APPLY
,因为它允许使用TOP(1)
和ORDER BY
的相关子查询:
insert into @tbl_shrprice (sharecode,shrprice,logdate)
values(1000, 10,'2016-02-10') , (1000, 12,'2016-02-20'),(1000, 18,'2016-02-25')
select p.*, np.nosshare, p.shrprice * np.nosshare as marketcap
from @tbl_shrprice p
cross apply (
select top(1) *
from @tbl_numshr n
where n.sharecode = p.sharecode
and n.logdate <= p.logdate
order by logdate desc
) as np
请注意,相关APPLY
对大型数据集的成本很高。我修改了价格的日期,以便在与股票数量相关时实际上有意义。