2015-11-15 45 views
12

私はリレーショナルデータベースを持っており、私の必要性に合っているので、string_agg()を使いたいと思います。

私がしたい:ここ
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

更新:コード僧侶 それはまだエラー@

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. 

質問:
私のクエリの何が問題になっているのですか?

答えて

26

はこれを試してみてください:

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

String_agg機能がquiz_idが整数であるためにのみ、あなたがエラーを取得している文字列値で動作します。

私はcharacter varyingに変換し、データプロダクトIDをグループ化するためにグループを追加しました。

SQL Fiddle例:http://sqlfiddle.com/#!15/9dafe/1

+0

Oh!どうもありがとうございました。私はこのシーンの背後にある技術については知らなかった。 – Sarit

+0

stackoverflow緑色のチェックを入れる前に4分間待ちます。しばらくお待ちください。 :) – Sarit

+0

いいえ...受け入れる:) –

関連する問題