在视图中组合多个行值

时间:2016-12-22 11:51:11

标签: sql postgresql

我有以下查询

SELECT  ROW_NUMBER() OVER (ORDER BY a.created_at ASC) AS id,
        e.full_name AS employee_name, 
        de.name AS department_name, 
        CONCAT JOB DESCRIPTION NAMES AS job_description_names, 
        t.description AS training_description,
        t.state AS training_state,
        t.code AS training_code,
        t.sop_edition AS training_sop_edition,
        t.opened_at AS training_opened_at,
        lc.name AS location_name
FROM attendances a 
JOIN trainings t ON a.training_id = t.id 
JOIN locations lc ON t.location_id = lc.id 
JOIN id_labels lb ON a.label_id = lb.id 
JOIN employees e ON lb.employee_id = e.id 
JOIN departments de ON e.department_id = de.id 
JOIN duties du ON du.employee_id = e.id 
JOIN job_descriptions jd ON du.job_description_id = jd.id

我需要包含一个连接所有job description names

的列

我已经尝试了string_agg(job_descriptions.name, '-'),但似乎无法使用像我这样的复杂查询。

还有其他建议吗?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在加入之前在子查询中聚合:

SELECT
    ROW_NUMBER() OVER (ORDER BY a.created_at ASC) AS id,
    e.full_name AS employee_name, 
    de.name AS department_name, 
    job_description_names, 
    t.description AS training_description,
    t.state AS training_state,
    t.code AS training_code,
    t.sop_edition AS training_sop_edition,
    t.opened_at AS training_opened_at,
    lc.name AS location_name
FROM
    attendances a JOIN 
    trainings t ON a.training_id = t.id JOIN
    locations lc ON t.location_id = lc.id JOIN
    id_labels lb ON a.label_id = lb.id JOIN
    employees e ON lb.employee_id = e.id JOIN
    departments de ON e.department_id = de.id
    inner join
    (
        select
            employee_id,
            string_agg(jd.name, '-') as job_description_names
        from 
            duties du
            inner join
            job_descriptions jd on du.job_description_id = jd.id
        group by employee_id
    ) s on s.employee_id = e.id