Excel中的SQL查询的等价物“SELECT A.one,B.two FROM A INNER JOIN B ON A.three = B.three”

你如何在Excel中做“select连接”? 假设我想从表A中列出一列,从表B列出两列,他们都有三列。

我会做:

SELECT A.one, B.two FROM A INNER JOIN B ON A.three = B.three 

但是,而不是表格,我有一个Excel工作表中的几个选项卡。 如何在Excel中做上述查询的等价物?

假设您的工作表如下所示:

工作表Sheet1

在这里输入图像说明

Sheet2中

在这里输入图像说明

Sheet3 Cell A2中input公式

 =IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"") 

并在Sheet3 Cell B2中input以下公式

 =IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),Sheet1!$C$2:$C$8,0)),"") 

上面的公式都是数组公式,所以通过按Ctrl + Shift + Enter来提交。 根据需要拖放/复制。 请参阅图片以供参考。

在这里输入图像说明

————————————————– ————————————————– ——————-

如果您还想显示Sheet3 (这是我的样本表中的ID中的前两张的第三列,则在Cell A2input以下公式

 =IFERROR(SMALL(IF(COUNTIF(Sheet1!$C$2:$C$10,Sheet2!$C$2:$C$10),Sheet2!$C$2:$C$10),ROW(1:1)),"") 

这也是一个数组公式。 在Cell B2input

 =IFERROR(INDEX(Sheet1!$A$2:$A$8,MATCH(A2,Sheet1!$C$2:$C$8,0)),"") 

然后在Cell C2input

 =IFERROR(INDEX(Sheet2!$B$2:$B$8,MATCH(A2,Sheet2!$C$2:$C$8,0)),"") 

根据需要拖放/复制。 看下面的图片。

在这里输入图像描述

从@ ScottCraner的答案得到这个在这里 。

还有另一种方法来实现这一点,而不使用公式和VBA。 看看这是否有帮助。

您可以使用VBA和ADO直接使用SQL查询工作表。 只需将下面的代码添加到VBA模块中的Sub。 代码主要是样板除了rs.Open行和With Worksheets行,你应该修改,以适应您的特定情况。

 ' Set up connection Dim cn As Object Set cn = CreateObject("ADODB.Connection") ' Connection string for Excel 2007 onwards .xlsm files With cn .Provider = "Microsoft.ACE.OLEDB.12.0" .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _ "Extended Properties=""Excel 12.0 Macro;IMEX=1"";" .Open End With ' Connection string for Excel 97-2003 .xls files ' It should also work with Excel 2007 onwards worksheets ' as long as they have less than 65536 rows 'With cn ' .Provider = "Microsoft.Jet.OLEDB.4.0" ' .ConnectionString = "Data Source=" & ThisWorkbook.FullName & ";" & _ ' "Extended Properties=""Excel 8.0;IMEX=1"";" ' .Open 'End With ' Create and run the query Dim rs As Object Set rs = CreateObject("ADODB.Recordset") ' Join the two worksheets - assumed that these are named "Sheet1" ' and "Sheet2", the columns are named "one", "two" and "three" ' and that the results should be output to "Sheet3" rs.Open "SELECT [Sheet1$].[one], [Sheet2$].[two] " & _ "FROM [Sheet1$] INNER JOIN [Sheet2$] " & _ "ON [Sheet1$].[three] = [Sheet2$].[three];", cn ' Output the field names and the results Dim fld As Object Dim i As Integer ' Change the worksheet to whichever one you want to output to With Worksheets("Sheet3") .UsedRange.ClearContents For Each fld In rs.Fields i = i + 1 .Cells(1, i).Value = fld.Name Next fld .Cells(2, 1).CopyFromRecordset rs End With ' Tidy up rs.Close cn.Close 

该代码可以被改变,join到参考使用早期绑定,而不是“Microsoft ActiveX数据对象2.8库”(去工具>在VBA编辑引用做到这一点)。 您将更改以下几行声明和初始化各种ADO对象:

 Dim cn As ADODB.Connection Set cn = New ADODB.Connection Dim rs As ADODB.Recordset Dim fld As ADODB.Field