我有一个表,其列是动态的,除了一列:A。该表中还有一些空值(0n)。如何添加另一列显示每行的总和,并忽略具有" 0n"的列。在该特定行或取代0。 这是我的代码,它总和失败,也不会忽略空值。
addTotalCol:{[]
table:flip`A`B`C`D!4 4#til 9;
colsToSum: string (cols table) except `A; / don't sum A
table: update Total: sum (colsToSum) from table; / type error here. Also check for nulls
:table;
}
答案 0 :(得分:3)
我认为在您的情况下使用功能更新会更好:
addTotalCol:{[]
table:flip`A`B`C`D!4 4#til 9;
colsToSum:cols[table] except `A; / don't sum A
table:![table;();0b;enlist[`Total]!enlist(sum;enlist,colsToSum)];
:table;
}
它无法正常工作的原因是因为您的第四行被解析为:
table: update Total: sum (enlist"B";enlist"C";enlist"D") from table;
由于sum仅适用于数字,因此输入为字符串时返回'类型错误。
使用colsToSum作为字符串输入的另一种解决方案:
addTotalCol:{[]
table:flip`A`B`C`D!4 4#til 9;
colsToSum:string cols[table] except `A; / don't sum A
table:get"update Total:sum(",sv[";";colsToSum],") from table"
:table;
}
基本上,这将在字符串中构建查询,然后再在q中执行。
但是,功能更新仍然是首选。
编辑:完全回答总和0n:
addTotalCol:{[]
table:flip`A`B`C`D!4 4#0n,til 9;
colsToSum:cols[table] except `A; / don't sum A
table:![table;();0b;enlist[`Total]!enlist(sum;(^;0;enlist,colsToSum))];
:table;
}
答案 1 :(得分:1)
我认为这里有一个更清洁的版本没有功能形式。
q)//let us build a table where our first col is symbols and the rest are numerics,
/// we will exclude first from row sums
q)t:flip `c0`c1`c2`c3!(`a`b`c`d;1 2 3 0N;0n 4 5 6f;1 2 3 0Nh)
q)//columns for sum
q)sc:cols[t] except `c0
q)///now let us make sure we fill in each column with zero,
/// add across rows and append as a new column
q)show t1:t,'flip enlist[`sumRows]!enlist sum each flip 0^t sc
c0 c1 c2 c3 sumRows
-------------------
a 1 1 2
b 2 4 2 8
c 3 5 3 11
d 6 6
q)meta t1
c | t f a
-------| -----
c0 | s
c1 | i
c2 | f
c3 | h
sumRows| f