1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQL の string_agg() で select 結果を文字列として連結

1
Posted at

やりたいこと

select した結果のレコードのフィールドを連結した文字列を取得する。
例えば、select の結果が id = 1, 2, 3 のレコードの場合、"1, 2, 3" の文字列を取得する。

select の結果を文字列として連結

テーブル定義例

create table test1 (
  id    integer generated always as identity primary key,
  name  varchar(32) not null
);

insert into test1 (name) values ('aaa');
insert into test1 (name) values ('bbb');
insert into test1 (name) values ('ccc');

string_agg()

string_agg({フィールド}, {セパレータ}) で select の結果を文字列として連結することができる。

# select string_agg(id::text, ', ' order by id asc) from test1;

 string_agg
------------
 1, 2, 3
(1 row)

同一レコードの複数のフィールドを連結したい場合には、concat() でフィールド単位で連結した結果を、レコード毎に連結することができる。

# select string_agg(concat(id::text, ':', name), ', ' order by id asc) from test1;

     string_agg
---------------------
 1:aaa, 2:bbb, 3:ccc
(1 row)

フィールド毎に string_agg() で連結することもできる。

# select
    string_agg(id::text, ', ' order by id asc),
    string_agg(name, ', ' order by id asc)
   from test1;

 string_agg |  string_agg
------------+---------------
 1, 2, 3    | aaa, bbb, ccc
(1 row)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?