【问题标题】:string_agg No function matches the given namestring_agg 没有与给定名称匹配的函数
【发布时间】:2015-11-15 08:02:47
【问题描述】:

我有关系数据库,想使用 string_agg(),因为它似乎符合我的需要。

我想要:

product_id | quiz_id
-----------+----------
         1 | 1,6
         2 | 2,7
         3 | 3,8
         4 | 4

这是我的数据库。

    select quiz_id , product_id, lastmodified from dugong.quiz;
 quiz_id | product_id |         lastmodified          
---------+------------+-------------------------------
       1 |          1 | 2015-11-11 14:46:55.619162+07
       2 |          2 | 2015-11-11 14:46:55.619162+07
       3 |          3 | 2015-11-11 14:46:55.619162+07
       4 |          4 | 2015-11-11 14:46:55.619162+07
       5 |          5 | 2015-11-11 14:46:55.619162+07
       6 |          1 | 2015-11-11 14:46:55.619162+07
       7 |          2 | 2015-11-11 14:46:55.619162+07
       8 |          3 | 2015-11-11 14:46:55.619162+07

我的尝试:
请参阅文档。 How to concatenate strings of a string field in a PostgreSQL 'group by' query? http://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES

select product_id , string_agg(quiz_id, ',' order by lastmodified) from dugong.quiz;
ERROR:  function string_agg(integer, unknown) does not exist
LINE 1: select product_id , string_agg(quiz_id, ',' order by lastmod...
                            ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.


Postgres 版本:
PostgresApp 9.4.4.1

更新:
@code-monk 还是报错。

select product_id , string_agg(quiz_id::int, ',' order by lastmodified) from dugong.quiz;
ERROR:  function string_agg(integer, unknown) does not exist
LINE 1: select product_id , string_agg(quiz_id::int, ',' order by la...
                            ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.

问题:
我的查询有什么问题?

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    试试这个:

    select product_id , string_agg(quiz_id::character varying, ',' order by lastmodified) 
    from quiz group by product_id;
    

    String_agg 函数仅适用于字符串值,您会收到错误,因为quiz_id 是整数。

    我已将其转换为 character varying 并添加了 group by 以对数据产品 ID 进行分组。

    SQL 小提琴示例:http://sqlfiddle.com/#!15/9dafe/1

    【讨论】:

    • 哦!非常感谢你。我从来不知道幕后的技术。
    • stackoverflow 让我等待 4 分钟,然后再进行绿色检查。请稍等片刻。 :)
    • 很好,完全忽略了数据类型......这成功了!
    • 或者干脆quiz_id::varchar
    • 有用的答案先生。我也想念数据类型。转换数据类型成功了。
    猜你喜欢
    • 2014-09-05
    • 1970-01-01
    • 2016-07-07
    • 2013-08-20
    • 2018-02-25
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多