PostgreSQL-如何在string_agg()中的每个条目上显示对应的字符串?

时间:2018-08-16 12:44:38

标签: postgresql select string-aggregation

我有2张桌子:

Employee
ID   Name
1    John
2    Ben
3    Adam

Employer
ID   Name
1    James
2    Rob
3    Paul

我想将string_agg()并将两个表串联在一条记录中作为单列。现在,我需要另一列,而不是确定该字符串是否来自“ Employee”表的列,如果数据来自“ Employer”表,它将显示“ Employee”和“ Employer”。

这是我显示表格的代码:

SELECT string_agg(e.Name, CHR(10)) || CHR(10) || string_agg(er.Name, CHR(10)), PERSON_STATUS
FROM Employee e, Employer er

这是我的预期输出:

ID    Name    PERSON_STATUS
1     John    Employee
      Ben     Employee
      Adam    Employee
      James   Employer
      Rob     Employer
      Paul    Employer

注意:我知道可以通过在表中添加另一列来完成此操作,但这种情况并非如此。这只是说明我的问题的一个例子。

3 个答案:

答案 0 :(得分:0)

根据您的样本,我想说您需要UNION ALL而不是合计:

SELECT id, name, 'Employee'::text AS person_status
FROM employee
UNION ALL
SELECT id, name, 'Employer'::text
from employer;

答案 1 :(得分:0)

好,所以首先我们将2个表合并为3列。我们可以通过这种方式选择任意值。

select
    "ID", -- Double quotes are necesary for capitalised aliases
    "Name",
    'Employee' as "PERSON_STATUS"
from
    employee
union
select
    "ID",
    "Name",
    'Employer'
from
    employer

然后我们对其进行子查询并根据需要执行我们的字符串操作。

select
    string_agg(concat(people."Name", '    ', people."PERSON_STATUS"), chr(10))
from
    (
        select
            "ID",
            "Name",
            'Employee' as "PERSON_STATUS"
        from
            employee
        union
        select
            "ID",
            "Name",
            'Employer'
        from
            employer
    ) as people

答案 2 :(得分:0)

SELECT 1 AS id, STRING_AGG(name, E'\r\n') AS name, STRING_AGG(person_status, E'\r\n') AS person_status
FROM (
        SELECT name, 'Employee' AS person_status
        FROM employee
        UNION ALL
        SELECT name, 'Employer'
        FROM employer
) data

返回:

enter image description here