我有一个带有主键和多个标记的表,可以设置为 1 或 0。
这就是表格的样子:
我的最终表有 108 个 m 值。
我想知道每行有多少个1。例如
ID | Sum_True
123 | 1
253 | 3
548 | 1
112 | 3
256 | 3
363 | 1
我为你做了一个 C++ 上的 UDSFs 模板,源代码你可以在 here 找到。已在
Vertica Analytic Database v8.1.1-10
上测试。
如果您能更好地定义您的需求(编程语言[C++/Java/Python]、Vertica版本、函数签名等),我可以改进代码。
数据:
dbadmin=> select * from eldj;
id | m01 | m02 | m03 | m04 | m05
-----+-----+-----+-----+-----+-----
112 | 0 | 0 | 1 | 1 | 1
123 | 0 | 0 | 1 | 0 | 0
253 | 1 | 1 | 0 | 1 | 1
256 | 1 | 1 | 0 | 0 | 0
363 | 0 | 1 | 0 | 0 | 0
548 | 0 | 0 | 0 | 0 | 1
(6 rows)
用途:
dbadmin=> select id, rowsum(*) - id as 'SUM_TRUE' from eldj;
id | SUM_TRUE
-----+----------
112 | 3
123 | 1
253 | 4
256 | 2
363 | 1
548 | 1
(6 rows)
编译:
下载源代码到
/tmp
文件夹。
g++ -D HAVE_LONG_INT_64 -I /opt/vertica/sdk/include \
-Wall -shared -Wno-unused-value -fPIC \
-o /tmp/RowSumUDSFs.so /tmp/RowSumUDSFs.cpp /opt/vertica/sdk/include/Vertica.cpp
安装:
DROP LIBRARY IF EXISTS RowSumUDSFs CASCADE;
CREATE OR REPLACE LIBRARY RowSumUDSFs AS '/tmp/RowSumUDSFs.so';
CREATE OR REPLACE FUNCTION rowsum AS LANGUAGE 'C++' NAME 'RowSumFactory' LIBRARY RowSumUDSFs;
我添加到函数参数
exclude
,以防列不是 int
数据类型。
示例:
daniel=> select * from eldj ;
col | m01 | m02 | m03 | m04 | m05
------+-----+-----+-----+-----+-----
key1 | 0 | 0 | 1 | 0 | 0
key2 | 1 | 1 | 0 | 1 | 1
key3 | 0 | 0 | 0 | 0 | 1
key4 | 0 | 0 | 1 | 1 | 1
key5 | 1 | 1 | 0 | 0 | 0
key6 | 0 | 1 | 0 | 0 | 0
(6 rows)
daniel=> select col, rowsum(* using parameters exclude='col') as 'SUM_TRUE' from eldj;
col | SUM_TRUE
------+----------
key1 | 1
key2 | 4
key3 | 1
key4 | 3
key5 | 2
key6 | 1
(6 rows)
应该是简单的添加列
select id, m1+m2+m3+m4+m5 as sum_true
from my_table
对于 108 列,您可以动态构建 SQL 代码字符串 e。使用模式信息,例如。对于列https://my.vertica.com/docs/7.0.x/HTML/index.htm#Authoring/SQLReferenceManual/SystemTables/CATALOG/COLUMNS.htm
select col,m01+m02+m03+m04+m05 as SUM_TRUE from eldj