How to get the values seperated by comma in a single column using SQL

亡梦爱人 提交于 2021-02-11 15:41:42

问题


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 a dept_id that is the primary key (no duplicates).
  • Your table that is called department should really be called employee_departments because it is a junction table, combining two different entities.
  • This table should be using emp_id as the link to employee, not name. That is, the foreign key relationship should be to the primary key of employee.


来源:https://stackoverflow.com/questions/55047955/how-to-get-the-values-seperated-by-comma-in-a-single-column-using-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!