问题
I have the below table and expected result. Please let me know if it is possible to achieve the result. Please refer the picture attached.
回答1:
You can use listagg()
:
select e.id, e.name, e.sal,
listagg(d.dept, ',') within group (order by d.dept_id) as depts,
listagg(d.dept_id, ',') within group (order by d.dept_id) as dept_ids,
from employee e left join
department d
on e.name = d.name
group by e.id, e.name, e.sal;
Some comments on the data model.
- Your
department
table should have adept_id
that is the primary key (no duplicates). - Your table that is called
department
should really be calledemployee_departments
because it is a junction table, combining two different entities. - This table should be using
emp_id
as the link toemployee
, notname
. That is, the foreign key relationship should be to the primary key ofemployee
.
来源:https://stackoverflow.com/questions/55047955/how-to-get-the-values-seperated-by-comma-in-a-single-column-using-sql