我有一张表,比如说它叫raw sheet
:
Column Index | A | B |
David | 1 | 10 |
Jerry | 5 | 15 |
David | 1 | 50 |
Jerry | 6 | 20 |
David | 8 | 20 |
列索引中只有有限的值。就像在这种情况下只有“大卫”和“杰里”。
我想创建另一个工作表,比如称为summary sheet
,它可以按列索引值汇总一些值,如下所示:
Column Index Summary | f(A,B) |
David | some value |
Jerry | some value |
f(A,B)可以是任何一种利用第一张纸中所有值的函数。一个例子:添加每一行的A * B以获得一个新数字。在这种情况下,它将是:
Column Index Summary | f(A,B) |
David | 220 | that is 1*10 + 1*50 + 8*20
Jerry | 195 | that is 5*15 + 6*20
我该怎么办?
答案 0 :(得分:1)
这是适用于您的Google表格自定义功能。它将在任意数值数据表上运行,通过任意(但简单)的代数表达式聚合数字。 (表达式必须在Javascript中有效,例如"A * B"
,"A + B / C"
,甚至"Math.pow(A,B)"
。)没有错误检查,所以它不是万无一失的。
示例:
=summary('raw sheet'!A1:C6,"A*B")
是的,你可以参考不同的表格。
=summary(A1:C6,"A*A + B")
=summary(A1:C6,"Math.pow(A,B)")
/**
* Performs given formula on each row in table, aggregating (summing)
* row results by the key value in first column.
*
* See: http://stackoverflow.com/questions/26925283/how-do-i-get-add-and-sum-by-column-index-value-in-google-spreasheet/26942156#26942156
*
* @param {range} table Input data table, including headers
* @param {string} formula Mathematical function to peform on each
* row in table, using header values as
* function parameters.
* @param {int} sortType (Optional, default 1) 0: do not sort, 1: sort ascending, -1: sort descending
* @param {int} sortColumn (Optional, default 1) Column to sort by.
*
* @return {range} Summary table of results
* @customfunction
*/
function summary(table,formula,sortType,sortColumn) {
sortType = (sortType == undefined) ? 1 : sortType;
sortColumn = (sortColumn == undefined) ? 1 : sortColumn;
// Sort comparison function for ordering summary table
// uses sortType & sortColumn
function colCompare(a,b)
{
var col = sortColumn - 1;
var order = sortType;
if (!order) return 1;
else
return ((a[col] < b[col]) ? -order : ((a[col] > b[col]) ? order : 0));
}
var headers = table[0];
// Start results with its header row
var summaryTable = [[headers[0],String(formula)]];
// evaluate formula, replacing variables (headers) with references to table
for (var h = 1; h < headers.length; h++) {
var re = new RegExp(headers[h],"g");
formula = formula.replace( re, " table[row]["+parseInt(h)+"] " );
}
// Aggregate data by summing formula for each row
var summary = {};
for (var row=1; row<table.length; row++) {
var key = table[row][0];
if (!(key in summary))
summary[key] = 0;
summary[key] += eval( formula );
}
// Append aggregated rows to results, and return
for (key in summary) {
summaryTable.push([key,summary[key]]);
}
// Sort the results
headers = summaryTable.splice(0, 1);
summaryTable.sort(colCompare).unshift(headers[0]);
return summaryTable;
}
编辑: 11月17日 - 添加了排序功能
答案 1 :(得分:0)
假设您在Col A中有名称,并且该示例的col A实际上是Col B, 在摘要表中,尝试类似:
=ArrayFormula(query({'raw sheet'!A2:A,'raw sheet'!B2:B*'raw sheet'!C2:C}, "select Col1, sum(Col2) where Col1 <>'' group By Col1 label sum(Col2) 'TOTAL' "))