【问题标题】: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 

提前谢谢你!

【问题讨论】:

标签: oracle plsql


【解决方案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>

【讨论】:

    猜你喜欢
    • 2013-08-11
    • 2023-03-07
    • 2010-11-06
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2012-12-22
    相关资源
    最近更新 更多