这对于有 SQL 经验的人(在本例中为 MS-Access)来说是一个挑战
我有 2 个表格:持股
和 估值
。
holdings
包含特定帐户在给定日期持有的所有 Assets 及其各自的值(value)。这些是字段:
id
{primary key/auto-inc}、accountid
{int}、holdingdate
{date}、holdingid
{int}, 持有值
{double}
估值
包含特定帐户在给定日期持有的总和。这些是字段:
id
{primary key/auto-inc}、accountid
{int}、评估日期
{date}、评估
{双}。
2012 年 1 月后,对于 valuations
表中的每个 valuation
,我在 holdings
表中都有相应的持股集合,其总值(value) =估值。
在此日期之前,我只有估值,没有持股。
例如,在评估
中,我会有这样的记录:
id | accountid | valuationdate | valuation
------------------------------------------------
56 | 12345 | 2013-03-31 | 2000000
相应地,我将持有这些 Assets (总计为该帐户在该日期的估值
:
id | accountid | holdingdate | holdingid | holdingvalue
---------------------------------------------------------------
250 | 12345 | 2013-03-31 | 16 | 1000000
251 | 12345 | 2013-03-31 | 38 | 500000
252 | 12345 | 2013-03-31 | 27 | 500000
如上所述,有些情况下我只有valuations
表中的记录,而没有相应的持仓。
为了简化/优化我的数据库结构,我想消除 valuations
表,因为它本质上是通过简单求和来复制 holdings
表中应存在的信息给定日期帐户的 Assets 。为了获得客户 future 的估值,我可以简单地将他们在给定日期的持有量相加,完全不需要估值
表。
我的目标是使用 valuations
中不存在的日期的数据填充 holdings
表。
本质上,如果帐号/评估日期组合不存在持仓,则将虚拟持仓 (holdingid = 999
) 插入到该帐号/评估日期的持仓表中,等于评估日期那个日期。
是否可以构造一个 SQL 查询来实现上述目的?
最佳答案
其中之一应该有效:
insert into holdings (accountid, holdingdate, holdingid, holdingvalue)
select v.accountid, v.valuationdate, 999, v.valuation
from valuations v
left join holdings h on h.accountid=v.accountid and h.holdingdate=v.valuationdate
where h.holdingdate is null
EDIT: Corrected the second version to use a correlated WHERE clause.
insert into holdings (accountid, holdingdate, holdingid, holdingvalue)
select v.accountid, v.valuationdate, 999, v.valuation
from valuations v
where v.valuationdate not in (select distinct holdingdate from holdings where accountid=v.accountid)
关于sql - 构造 SQL 查询以使用另一个表中的数据填充一个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989409/