首页 > 解决方案 > 在 google app 脚本中咨询 group by

问题描述

我正在寻找的是,对于我拥有的桌子,我可以根据我实施的一些条件进行分组

在此处输入图像描述

我有这张桌子,我称之为:

Codigo.gs

function pendiente_inci(){

 var hojaCalculo = SpreadsheetApp.openById("1XkGF_rmsuOM_iFFKWI1-TTu6GMdHTsdjhasf");
 var hojaDatos = hojaCalculo.getSheetByName('Data');
 var numColumns = hojaDatos.getLastColumn();
 var ultimaFila = hojaDatos.getLastRow();

  var row = hojaDatos.getRange(1, 1, ultimaFila, numColumns).getValues();

  return row.lenght;
 }

在这里,我正在调用图像中显示的所有表格,但我要调用的是我拥有的工人的“待处理”数量。对数据库进行查询是这样的:

 select usuario,count(*) from Data where estado="pendiente" group by usuario

我该怎么做才能在我的 code.gs 中进行此查询?

标签: google-apps-script

解决方案


您需要遍历.getValues()调用返回的数据。请注意,它返回值的二维数组。

  var valores = hojaDatos.getRange(1, 1, ultimaFila, numColumns).getValues();
  var usuarios = {}; // This will contain the results
  for (var i = 1; i < valores.length; i++) { // Skip the header row by starting with i = 1
    var row = valores[i]; // This is the entire row
    var estado = row[2]; // Assuming "estado" is in column C. This is equivalent to writing valores[i][2].
    if (estado == "pendiente") {
      var nombre = row[1]; // Assuming "usuario" is in column B. This is equivalent to writing valores[i][1].

      // If the user does not exist in the users object, add them. Set the count of jobs to zero.
      if (!usuarios.hasOwnProperty(nombre)) {
        usuarios[nombre] = { trabajos: 0 };
      }

      // Increment the user's job count
      usuarios[nombre].trabajos++;
    }
  }

一旦你浏览了数据并计算出你想要的东西,你就可以做任何其他事情。我不清楚你发布的代码的目标是什么,但至少你可以Logger.log()它。

function pendiente_inci() {
  var hojaCalculo = SpreadsheetApp.openById("1XkGF_rmsuOM_iFFKWI1-TTu6GMdHTsdjhasf");
  var hojaDatos = hojaCalculo.getSheetByName('Data');
  var numColumns = hojaDatos.getLastColumn();
  var ultimaFila = hojaDatos.getLastRow();

  var valores = hojaDatos.getRange(1, 1, ultimaFila, numColumns).getValues();
  var usuarios = {}; // This will contain the results
  for (var i = 1; i < valores.length; i++) { // Skip the header row by starting with i = 1
    var row = valores[i]; // This is the entire row
    var estado = row[2]; // Assuming "estado" is in column C. This is equivalent to writing valores[i][2].
    if (estado == "pendiente") {
      var nombre = row[1]; // Assuming "usuario" is in column B. This is equivalent to writing valores[i][1].

      // If the user does not exist in the users object, add them. Set the count of jobs to zero.
      if (!usuarios.hasOwnProperty(nombre)) {
        usuarios[nombre] = { trabajos: 0 };
      }

      // Increment the user's job count
      usuarios[nombre].trabajos++;
    }
  }

  Logger.log(JSON.stringify(usuarios));
}

推荐阅读