代码之家  ›  专栏  ›  技术社区  ›  2Big2BeSmall

从函数PostgreSQL而不是record返回多个列和行

  •  5
  • 2Big2BeSmall  · 技术社区  · 7 年前

    我在线阅读了PostgreSQL上的函数并返回结果 在此链接中:

    1. SQL function return-type: TABLE vs SETOF records
    2. How do I reference named parameters in Postgres sql functions?
    3. http://www.postgresqltutorial.com/plpgsql-function-returns-a-table/

    我编写了此函数:

    create or replace function brand_hierarchy(account_value int)
      RETURNS table (topID INTEGER, accountId INTEGER, liveRowCount bigint,archiveRowCount bigint)
      AS
    $BODY$
      SELECT * FROM my_client_numbers
    where accountId  = coalesce($1,accountId);
    $BODY$
    LANGUAGE sql;
    

    它可以工作并在单列类型的记录中返回结果。 请注意,可能会返回多行。

    现在的回答是:

    record
    (1172,1172,1011,0)
    (1172,1412,10,40)
    .....
    

    我希望得到的结果不是记录,而是多个列

    |---------|---------|------------|----------------|
    | topID   |accountId|liveRowCount|archiveRowCount |
    |---------|---------|------------|----------------|
    | 1172    |1172     | 1011       |  0             |
    | 1172    |1412     | 10         |  40            |
    

    有没有办法从PostgreSQL函数返回多个列

    3 回复  |  直到 7 年前
        1
  •  8
  •   a_horse_with_no_name    7 年前

    返回表(或集合)的函数应在FROM子句中使用:

    select * 
    from brand_hierarchy(1234)
    
        2
  •  2
  •   2Big2BeSmall    6 年前

    通过此查询,我可以按预期看到它:

    SELECT * FROM brand_hierarchy (id)
    
        3
  •  0
  •   Mohammed    4 年前

    我找到了这个函数 crosstab 我想这就是你要找的 https://www.postgresql.org/docs/9.3/tablefunc.html