MS Access:将第一次出现的事件与第一次出现的事件相连接,并将第二次出现的事件与第二个事件相联系

时间:2018-10-20 00:42:36

标签: sql-server ms-access

示例:我有第一个表,

Table1

第二张桌子

Table2

我想根据编号和名称查询将这两个表连接起来。但是,由于数字和名称并不总是唯一的,所以我最终得到了多种组合。我希望第一个表中的第一个匹配项与第二个表中的第一个匹配项相匹配,第二个匹配项与第二个表中的匹配项如下所示:

Result

任何解决此问题的想法都值得赞赏:)

1 个答案:

答案 0 :(得分:2)

向每个表添加一个自动编号字段。不需要指定为主键。如果您的数据在SQLServer后端,则不知道如何创建唯一标识符字段。

我修改了字段名称,因此在两个表中它们都不相同。

然后构建查询:

Query1

SELECT ID1, Number1, Name1, DCount("*","Table1","Name1 = '" & [Name1] & "' AND Number1=" & [Number1] & " AND ID1<=" & [ID1]) AS GrpSeq1
FROM Table1;

Query2

SELECT ID2, Number2, Name2, Letter, DCount("*","Table2","Name2 = '" & [Name2] & "' AND Number2=" & [Number2] & " AND ID2<=" & [ID2]) AS GrpSeq2
FROM Table2;

Query3

SELECT Query1.Number1, Query1.Name1, Query1.GrpSeq1, Query2.Letter
FROM Query2 RIGHT JOIN Query1 ON (Query2.Number2 = Query1.Number1) AND (Query2.Name2 = Query1.Name1) AND (Query2.GrpSeq2 = Query1.GrpSeq1);

我认为有一种方法可以使用嵌套SQL代替DCount()。无论哪种方式,对于大型数据集,预期性能都会降低。

全合一:

SELECT Query1.Number1, Query1.Name1, Query1.GrpSeq1, Query2.Letter
FROM (SELECT Table2.ID2, Table2.Number2, Table2.Name2, DCount("*","Table2","Name2 = '" & [Name2] & "' AND Number2=" & [Number2] & " AND ID2<=" & [ID2]) AS GrpSeq2, Table2.Letter FROM Table2) AS Query2 
RIGHT JOIN (SELECT Table1.ID1, Table1.Number1, Table1.Name1, DCount("*","Table1","Name1 = '" & [Name1] & "' AND Number1=" & [Number1] & " AND ID1<=" & [ID1]) AS GrpSeq1 FROM Table1) AS Query1 
ON (Query2.GrpSeq2 = Query1.GrpSeq1) AND (Query2.Name2 = Query1.Name1) AND (Query2.Number2 = Query1.Number1);