2015-11-15 18 views
12

Mam relacyjną bazę danych i chciałbym użyć string_agg(), ponieważ wydaje mi się to pasować do moich potrzeb.

chcę:
string_agg Żadna funkcja nie pasuje do podanej nazwy

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

Oto moja baza.

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 

Moja próba:
Patrz dokument. 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

wersja
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

Aktualizacja:
@ code-mnicha Nadal błędu.

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. 

Pytanie:
Co jest nie tak z moim zapytaniu?

Odpowiedz

26

Spróbuj tego:

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

String_agg funkcja działa tylko z wartościami Smyczkowych, otrzymujesz błąd, ponieważ quiz_id jest liczbą całkowitą.

Przekonwertowałem go na character varying i dodano grupę według grupowania identyfikatora produktu danych.

SQL Fiddle Przykład: http://sqlfiddle.com/#!15/9dafe/1

+0

Oh! Dziękuję Ci bardzo. Nigdy nie wiedziałem o technice za sceną. – Sarit

+0

stackoverflow Pozwól mi czekać 4 minuty przed położyć zielony czek. Proszę poczekaj chwilę. :) – Sarit

+0

Okay ... zaakceptuj wtedy :) –

Powiązane problemy