PostGres - 从表中获取每列中前 5 个频繁值

问题描述 投票:0回答:1

我的表可以有 100 列。

我们不需要 5 行。我们也可以有一行,其中的值连接起来。

我可以使用以下查询从单列中选择前 5 个频繁值

SELECT col1 FROM table GROUP BY col1 ORDER BY count(*) DESC LIMIT 5

但我想要每列中前 5 个频繁值。我正在尝试使用WITH子句,例如。

WITH top_5_col1 AS (
    SELECT col1 FROM table GROUP BY col1 ORDER BY count(*) DESC LIMIT 5
),
top_5_col2 AS (
    SELECT col2 FROM table GROUP BY col2 ORDER BY count(*) DESC LIMIT 5
)
SELECT 
    STRING_AGG(top_5_col1.col1, ','::text) as col1,
    STRING_AGG(top_5_col2.col2, ','::text) as col2
FROM top_5_col1, top_5_col2;

可能有数百个列。 有什么更好的方法可以实现这一目标?

postgresql
1个回答
0
投票

最好写一个这样的函数

CREATE OR REPLACE FUNCTION pizza_runner.f_count_top5(table_name varchar, column_name varchar, schema_name varchar)
 RETURNS text
 LANGUAGE plpgsql
AS $function$
declare 
t_sql text;
ret text;
    begin
        t_sql := 'select STRING_AGG('|| column_name ||', '',''::text) as '|| column_name ||' from (SELECT '|| column_name ||' FROM '||schema_name||'.'||table_name ||' GROUP BY '|| column_name ||' ORDER BY count(*) DESC LIMIT 5) q1';
        EXECUTE format(t_sql) into ret;
        return ret;
    END;
$function$
;

使用 information_schema 来计算前 5 个值后

select f_count_top5(table_name::varchar, column_name::varchar, table_schema::varchar) from 
information_schema.columns
where "columns".table_schema = 'pizza_runner' and table_name = 't1'
© www.soinside.com 2019 - 2024. All rights reserved.