pgsql多行合并方法,将结果返回为逗号分隔的列表

--公式
STRING_AGG(expression, separator)

  

CREATE TABLE employees (
    id SERIAL PRIMARY KEY,
    name VARCHAR(50),
    department VARCHAR(50)
);

INSERT INTO employees (name, department) VALUES
    ('John', 'Sales'),
    ('Jane', 'HR'),
    ('David', 'Finance'),
    ('Sarah', 'Sales');

  

SELECT department, STRING_AGG(name, ',') AS employees_list
FROM employees
GROUP BY department;
SQL
上述查询将返回类似于以下结果:

  department  |   employees_list   
--------------+--------------------
 Sales        | John,Sarah
 HR           | Jane
 Finance      | David

借鉴地址:https://deepinout.com/sql/sql-questions/76_sql_postgresql_query_to_return_results_as_a_comma_separated_list.html

posted @ 2023-11-07 11:14  天涯已可  阅读(317)  评论(0编辑  收藏  举报