【问题标题】:grouping by parameters in postgres sql function and returning column name identical to the parameter在postgres sql函数中按参数分组并返回与参数相同的列名
【发布时间】:2022-01-16 08:58:04
【问题描述】:

我有一个问题

select count(distinct id), usertype from mytable group by usertype;

我想把它包装在一个以用户类型为参数的函数中

create or replace function myfun(facet text)
RETURNS TABLE(total_accounts bigint, facet text)

LANGUAGE plpgsql
AS $$
    select count(distinct id), facet from mytable group by facet;
$$;
select * from myfun('usertype');

所以输出列名也取决于我发送的参数。

但它显示错误“参数方面被多次使用”。

当我将 'usertype' 作为参数传递时,如何使输出与原始查询相同?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您可以在 plpgsql 函数中使用动态查询:

    create or replace function myfun(OUT total_accounts bigint, INOUT facet text)
    RETURNS setof record LANGUAGE plpgsql
    AS $$
    BEGIN
        RETURN QUERY EXECUTE '
        select count(distinct id),' || quote_ident(facet) || ' from mytable group by ' || quote_ident(facet) ;
    END ;
    $$;
    
    select * from myfun('usertype');
    

    测试结果在dbfiddle

    【讨论】:

    • 嗯,它仍然给出一个错误“参数方面多次使用”......
    • 这是因为你有一个输入参数和一个名为'facet'的输出参数。我已经更改了您的函数的声明以使其现在可以工作,请参阅dbfiddle中的更新答案和测试@
    猜你喜欢
    • 1970-01-01
    • 2019-02-22
    • 2018-12-24
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-23
    • 2012-05-11
    相关资源
    最近更新 更多