string_agg:两个以上属性串联

tok*_*khi 1 postgresql string-aggregation

我正在使用postgresql 9.0 我想知道是否可以将三个属性连接在一起。

这就是我连接两个属性(书本和逗号)的方式:

SELECT string_agg(book, ',') FROM authors where id = 1;


| book1,book2,book3|
--------------------
Run Code Online (Sandbox Code Playgroud)

我怎样才能做如下的事情:

SELECT string_agg(name, ':', book, ',') FROM authors where id = 1;

| Ahmad: book1,book2,book3|
  ----------------
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙吗?谢谢。

Kla*_*äck 5

只需像这样连接字段:

SELECT name || ':' || string_agg(book, ',') FROM authors where id = 1;
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您的 SQL 返回多个名称,您需要按名称分组(如果您有多个同名作者,则情况会变得更复杂。我不会在这个答案中讨论这种情况):

SELECT name || ':' || string_agg(book, ',') 
  FROM authors where id = 1 
 GROUP BY name;
Run Code Online (Sandbox Code Playgroud)

如果您想要按字母顺序排列书籍,您可以ORDER BY为书籍添加:

SELECT name || ':' || string_agg(book, ',') WITHIN GROUP ORDER BY book 
  FROM authors where id = 1 
 GROUP BY name;
Run Code Online (Sandbox Code Playgroud)