sql - 构造 SQL 查询以使用另一个表中的数据填充一个表

标签 sql ms-access

这对于有 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/

相关文章:

sql - 查找具有相同id的记录并放在同一行

vba - 如何以 PDF 格式输出报告,其中名称由字段中的值组成?

ms-access - Access 更改表 "Allow Zero Length"

sql - Access 2013 : Why am I getting this Syntax Error?

sql - 在 Postgres JOIN 查询中区分 null 和 empty

php - 调用非对象成员函数

mysql - 按年调优sql

mysql - 计算员工上个月在工作场所花费的每天平均小时数

python - 如何在access数据库中创建小数字段?

python - 使用 Pandas 读取 Access 表的最简单方法?