我有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
注意:我知道可以通过在表中添加另一列来完成此操作,但这种情况并非如此。这只是说明我的问题的一个例子。
答案 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)