我需要对Netezza系统进行行计数,但只有2列具有特定值
我有
SELECT TABLENAME, RELTUPLES
FROM _V_TABLE
WHERE objtype = 'TABLE' and tablename like 'MY%STUFF'
这将显示所有表名及其行数
但是我需要在其中添加一个where子句。 columnA = 1,columnB = ABC,
每个表都包含这两个列名。
由于
克雷格
答案 0 :(得分:0)
如果要通过SQL执行此操作,则可以使用存储过程完成此操作。这是一个存储过程,可以执行我认为您要求的操作。
我的假设是您只想计算实际匹配指定列值的表中的行,因此_v_tables中的RELTUPLES不会用于此。示例存储过程代码还假定每个列都是varchar(1000)。如果要匹配其他数据类型,则必须更改代码。
在创建存储过程之前,创建一个如下所示的引用表:
create table reftable_sp_row_count (tablename varchar(1000), rowcount bigint) distribute on random;
然后像这样创建存储过程:
CREATE OR REPLACE PROCEDURE SP_ROW_COUNT(VARCHAR(254), VARCHAR(254), VARCHAR(254), VARCHAR(254), VARCHAR(254))
RETURNS REFTABLE(REFTABLE_SP_ROW_COUNT)
EXECUTE AS OWNER
LANGUAGE NZPLSQL AS
BEGIN_PROC
DECLARE
pTablePattern ALIAS FOR $1;
pColOneName ALIAS FOR $2;
pColOneValue ALIAS FOR $3;
pColTwoName ALIAS FOR $4;
pcolTwoValue ALIAS FOR $5;
vRecord RECORD;
BEGIN
for vRecord in
EXECUTE 'SELECT schema
|| ''.''
|| tablename tablename
FROM _v_table v
WHERE tablename LIKE ''' || upper(pTablePattern) || '''
AND EXISTS
(
SELECT attname
FROM _v_relation_column c
WHERE c.objid = v.objid
AND attname = ''' || upper(pColOneName) || '''
)
AND EXISTS
(
SELECT attname
FROM _v_relation_column c
WHERE c.objid = v.objid
AND attname = ''' || upper(pColTwoName) || '''
)'
LOOP
EXECUTE IMMEDIATE 'INSERT INTO ' || REFTABLENAME ||
' SELECT ''' || vRecord.tablename || ''' , COUNT(1) from ' || vRecord.tablename ||
' where ' || upper(pColOneName) || ' = ''' || pColOneValue || ''' and ' || upper(pColTwoName) || ' = ''' || pColTwoValue || ''' ;';
-- Note that if you change the data types for a given column to a different type then you'll want to change ''' || pColOneValue || ''' to ' || pColOneValue || ' as appropriate
END LOOP;
RETURN REFTABLE;
END;
END_PROC;
以下是一些示例输出。
TESTDB.ADMIN(ADMIN)=> select * from table_1 order by colA, colB;
COLA | COLB
------+------
ABC | BLUE
ABC | BLUE
ABC | BLUE
ABC | RED
ABC | RED
(5 rows)
TESTDB.ADMIN(ADMIN)=> select * from table_2 order by colA, colB;
COLA | COLB
------+--------
ABC | BLUE
ABC | BLUE
XYZ | BLUE
XYZ | BLUE
XYZ | YELLOW
(5 rows)
TESTDB.ADMIN(ADMIN)=> call sp_row_count('TABLE_%', 'COLA', 'ABC', 'COLB','BLUE');
TABLENAME | ROWCOUNT
---------------+----------
ADMIN.TABLE_1 | 3
ADMIN.TABLE_2 | 2
(2 rows)