我想显示以下数据的数据透视表。我有一张包含10000条记录的表格。
表:Mat_test
CREATE TABLE Mat_test AS
SELECT DISTINCT 1 + floor(random() * 1500000)::integer AS id,
2 + floor(random() * 1600000)::integer AS Numbers
FROM generate_series(1, 10000) g;
现在创建一个函数,我想从中显示上述记录的交叉表:
功能:Mat_test_cross_tab
CREATE OR REPLACE FUNCTION Mat_test_cross_tab (_retType anyelement
, table_name varchar)
RETURNS SETOF anyelement AS
$BODY$
DECLARE
query varchar;
cols varchar;
cols1 varchar;
cols2 varchar;
BEGIN
cols := 'SELECT string_agg(numbers::varchar,'','') from '||table_name||'';
execute cols into cols1;
cols1 := 'SELECT REPLACE('''||cols1||''','','','' " INT,"'')';
execute cols1 into cols2;
cols2 := '"'||cols2||'" INT';
raise info '%',cols2;
query := 'SELECT * FROM Crosstab
(
'' SELECT id,numbers,count(*) as t
from '||table_name||'
group by 1,2
order by 1,2'',
$$select distinct numbers from '||table_name||'$$
)
AS (id integer,'||cols2')';
RAISE INFO '%',query;
RETURN QUERY EXECUTE query;
END;
$BODY$ LANGUAGE PLPGSQL;
现在我正在创建用于创建用户定义类型的函数,以返回上述函数的结果集。
功能:Type_mat
CREATE OR REPLACE FUNCTION Type_mat(table_name varchar)
RETURNS VOID AS
$BODY$
DECLARE
query varchar;
cols varchar;
cols1 varchar;
cols2 varchar;
BEGIN
cols := 'SELECT string_agg(numbers::varchar,'','') from '||table_name||'';
execute cols into cols1;
cols1 := 'SELECT REPLACE('''||cols1||''','','',''" INT,"'')';
execute cols1 into cols2;
cols2 := '"'||cols2||'" INT';
query := 'CREATE TYPE Type_for_mat AS
(
id integer,
'||cols2||'
)';
RAISE INFO '%',query;
EXECUTE query;
END;
$BODY$ LANGUAGE PLPGSQL;
呼叫:
SELECT Type_mat('mat_test');
收到错误:
ERROR: tables can have at most 1600 columns