Google表格查询-两个范围之间的笛卡尔联接

Ash*_*ria 4 google-sheets google-sheets-api google-sheets-query

我们如何使用查询功能在Google Spreadsheet上的两个范围之间实现以下联接?

范围1

Model   Style
Nissan  Coupe
Nissan  Truck
Honda   Sedan
Honda   Hatchback
Toyata  Truck
Honda   Coupe
Run Code Online (Sandbox Code Playgroud)

范围2

Style       Engine
Coupe       1200 cc
Coupe       1500 cc
Sedan       1000 cc
Truck       2000 cc
Sedan       1800 cc
Hatchback   800 cc
Run Code Online (Sandbox Code Playgroud)

输出量

Model   Style       Engine
Nissan  Coupe       1200 cc
Nissan  Coupe       1500 cc
Honda   Sedan       1000 cc
Nissan  Truck       2000 cc
Honda   Sedan       1800 cc
Honda   Hatchback   800 cc
Honda   Coupe       1200 cc
Honda   Coupe       1500 cc
Toyata  Truck       2000 cc
Run Code Online (Sandbox Code Playgroud)

小智 5

我们通过query命令使用的数据可视化语言不支持任何形式的联接。可以使用自定义函数获得所需的结果。

它的格式是=cartesianJoin(arr1, arr2, col1, col2)前两个自变量是要联接的范围,其他两个是要进行联接的列号(相对于范围)。例如,在您的情况下,第一个数组可能在A2:B8中,第二个数组在D2:E8中。那么公式将是

=cartesianJoin(A2:B8, D2:E8, 2, 1)
Run Code Online (Sandbox Code Playgroud)

表示我们通过第一数组(B)的第二列等于第二数组(D)的第一列进行连接。

function cartesianJoin(arr1, arr2, col1, col2) {
  var output = [];
  for (var i = 0; i < arr1.length; i++) {
    var r1 = arr1[i];
    var matching = arr2.filter(function(r2) {
      return r1[col1 - 1] === r2[col2 - 1];
    }).map(function(r2) {
      var copyr2 = r2.slice(0);
      copyr2.splice(col2 - 1, 1);
      return r1.concat(copyr2);
    });
    output = output.concat(matching);
  }
  return output;                     
}
Run Code Online (Sandbox Code Playgroud)

逻辑:对于第一个数组(r1)的每一行,按相等性要求过滤第二个数组,然后将每个匹配的行连接到r1,首先删除匹配的列,这样它就不会出现两次。

屏幕截图:

片