【问题标题】:Ms access DB - merge two tables base on columnsMs access DB - 基于列合并两个表
【发布时间】:2021-03-04 14:15:23
【问题描述】:

我正在尝试将两个表合并到一个基础上:

app.custid = fin.custid and
app.appdate = fin.findate and
app.price = fin.pricx

什么都不等于创建一个新表。这两个表没有关系。

Table app
appid   custid    appdate    price   
1         1       10/10/20     20    
2         2       10/10/20     10    
3         1       11/10/20     30    
4         3       12/10/20     20    
5         1       13/10/20     20    


Table fin
finid   custid    findate    pricex     
1         1       10/10/20     20
2         2       11/10/20     10
3         1       11/10/20     20
4         3       12/10/20     20
5         1       13/10/20     20

输出:

Table app-new
appid   custid    appdate    price    pricex
1         1       10/10/20     20       20     => same custid, appdate=findate, price=pricex
2         2       10/10/20     10       null   => same custid, appdate not the same findate
3         1       11/10/20     30       null   => same custid, appdate=findate, price is not the same pricex
4         3       12/10/20     20       20     => same custid, appdate=findate, price=pricex
5         1       13/10/20     20       20     => same custid, appdate=findate, price=pricex

Table fin-new
finid   custid    findate    pricex   
2         2       11/10/20     10
3         1       11/10/20     20

【问题讨论】:

  • 您是否在进行查询,该查询将为您提供这些结果以供其他软件或其他查询使用 - 或者您是否真的想要复制将数据输出到 Access DB 文件中的新物理表中?
  • @Dai 更容易更正确。查询或表与我是堆栈相同...
  • appid 和 finid 呢?他们不应该也匹配吗?
  • @forpas 不匹配。我只解释了 3 列。

标签: sql database ms-access


【解决方案1】:

对于第一种情况,您需要 LEFTapp 连接到 fin

SELECT a.*, f.pricex
FROM app AS a LEFT JOIN fin AS f
ON f.custid = a.custid AND f.findate = a.appdate AND f.pricex = a.price

对于第二种情况,您可以使用NOT EXISTS

SELECT f.*
FROM fin AS f
WHERE NOT EXISTS (
  SELECT 1
  FROM app AS a 
  WHERE f.custid = a.custid AND f.findate = a.appdate AND f.pricex = a.price
)

或者使用finappLEFT 连接,过滤掉匹配的行:

SELECT f.*
FROM fin AS f LEFT JOIN app AS a
ON f.custid = a.custid AND f.findate = a.appdate AND f.pricex = a.price
WHERE a.appid IS NULL

【讨论】:

  • 在情况 1 中,如果我想添加 WHERE a.workid = 21 或 22 我该如何添加它。 WorkID 仅在应用表中。案例 1 正在处理其余部分。我将测试用例 2。
  • @PeterPan2020 您可以在查询末尾添加:WHERE a.workid IN (21, 22)
  • @forbas 如果想添加为 AND a.workid = 21 或 22。表格应用程序中的额外列不在表格鳍中。所有条件加一个来自表格应用程序。
  • 您可以在 WHERE 子句中为 table app 添加任意数量的条件,但不能为 table fin 添加。
  • @forbas SELECT a.*, f.pricex FROM app AS a LEFT JOIN fin AS f ON f.custid = a.custid AND f.findate = a.appdate AND f.pricex = a。我的意思是价格和 a.workid=21。
猜你喜欢
  • 1970-01-01
  • 2013-07-29
  • 2021-06-26
  • 2011-12-20
  • 1970-01-01
  • 2013-03-28
  • 1970-01-01
  • 2016-03-23
  • 1970-01-01
相关资源
最近更新 更多