19
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[PostgreSQL 9.0+] string_aggで順序を指定する

Last updated at Posted at 2015-12-23

あれどうやって書くんだっけとなったのでメモ

この記事が前提とする環境

PostgreSQL 9.0以上

やりたいこと

従業員を表すテーブルemployeesがあるとする。

employee_id department_id employee_name
1 1 佐藤
2 1 鈴木
3 1 高橋
4 2 田中
5 2 伊藤

このとき、部門ごとに、その部門に所属している従業員の一覧を/区切りで出力したい。
出力の一貫性を保つために従業員の順番はemployee_id順とする。

department_id employee_names
1 佐藤/鈴木/高橋
2 田中/伊藤

コード

SELECT
  department_id,
  string_agg(employee_name, '/' ORDER BY employee_id) AS employee_names
FROM
  employees
GROUP BY
  department_id
ORDER BY
  department_id;

参考リンク

postgresql - How to get result from string_agg() with a proper order by - Stack Overflow

19
13
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
19
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?