Skip to content

Instantly share code, notes, and snippets.

@GuillermoBlasco
Last active November 18, 2021 14:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuillermoBlasco/d399d8ac41a825e8b934 to your computer and use it in GitHub Desktop.
Save GuillermoBlasco/d399d8ac41a825e8b934 to your computer and use it in GitHub Desktop.
Google sheets query by column name
/**
* Enhances Google Sheets' native "query" method. Allows you to specify column-names instead of using the column letters in the SQL statement (no spaces allowed in identifiers)
*
* Sample : =query(data!A1:I,SQL("data!A1:I1","SELECT Owner-Name,Owner-Email,Type,Account-Name",false),true)
*
* Params : useColNums (boolean) : false/default = generate "SELECT A, B, C" syntax
* true = generate "SELECT Col1, Col2, Col3" syntax
* reference: https://productforums.google.com/forum/#!topic/docs/vTgy3hgj4M4
* by: Matthew Quinlan
*/
function SQL(rangeName, queryString, useColNums){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = ss.getRange(rangeName);
var row = range.getValues()[0];
for (var i=0; i<row.length; i++) {
if (row[i].length < 1) continue;
var re = new RegExp("\\b"+row[i]+"\\b","gm");
if (useColNums) {
var columnName="Col"+Math.floor(i+1);
queryString = queryString.replace(re,columnName);
}
else {
var columnLetter=range.getCell(1,i+1).getA1Notation().split(/[0-9]/)[0];
queryString = queryString.replace(re,columnLetter);
}
}
//Logger.log(queryString);
return queryString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment