如何将表数据连接到一个逗号分隔的列中[重复]
Posted
技术标签:
【中文标题】如何将表数据连接到一个逗号分隔的列中[重复]【英文标题】:How do I join table data into one comma separated column [duplicate] 【发布时间】:2021-12-07 08:08:00 【问题描述】:我有两个具有一对多关系的表:员工和他们工作的公司。比如:
表“员工”
ID | Name
=============
1 | Mike
2 | Diana
3 | Emily
表格“职位”
ID | Position | EmployeeID | StartDate | FinishDate | ...
=============
1 | Janitor | 1 | ....
2 | Dustman | 1 | ....
3 | Dishwasher | 2 | ...
如何编写一个 SQL 查询来告诉我 Mike 是清洁工和 Dustman,而 Diana 是洗碗机?每个信息都应在一行中显示。比如:
Employee | Positions
====================
Mike | Janitor, Dustman
Diana | Dishwasher
Emily | NULL
提前谢谢你!
【问题讨论】:
@gretal,您的链接指向一个 MS SQL Server 问题;这是 Oracle。 哦,我没注意到 .this 适用于 oracle:***.com/questions/45278653/… 【参考方案1】:带有聚合的外连接。第 1 - 11 行中的样本数据;查询从第 12 行开始:
SQL> with
2 employee (id, name) as
3 (select 1, 'Mike' from dual union all
4 select 2, 'Diana' from dual union all
5 select 3, 'Emily' from dual
6 ),
7 positions (id, position, employeeid) as
8 (select 1, 'Janitor' , 1 from dual union all
9 select 2, 'Dustman' , 1 from dual union all
10 select 3, 'Dishwasher', 2 from dual
11 )
12 select e.name,
13 listagg(p.position, ', ') within group (order by p.position) positions
14 from employee e left join positions p on p.employeeid = e.id
15 group by e.name
16 order by e.name;
NAME POSITIONS
----- ------------------------------
Diana Dishwasher
Emily
Mike Dustman, Janitor
SQL>
【讨论】:
以上是关于如何将表数据连接到一个逗号分隔的列中[重复]的主要内容,如果未能解决你的问题,请参考以下文章