简体   繁体   English

如何使用SQL在单列中获取逗号分隔的值

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

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. 请参考所附图片。

在此处输入图片说明

You can use listagg() : 您可以使用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). 您的department表应具有作为主键的dept_id (没有重复项)。
  • Your table that is called department should really be called employee_departments because it is a junction table, combining two different entities. 您称为department表实际上应该称为employee_departments因为它是结合两个不同实体的联结表。
  • This table should be using emp_id as the link to employee , not name . 该表应使用emp_id作为指向employee的链接,而不是name That is, the foreign key relationship should be to the primary key of employee . 也就是说,外键关系应该是employee的主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在sql中更新单个列中的多个逗号分隔值 - How to update multiple comma seperated values in a single column in sql 如何在SQL Server表中添加多个列作为单个逗号分隔值 - How to add more than a single column in a SQL Server table as individual comma seperated values 如何检查单个逗号分隔列中的多个值 - how to check multiple values in a single comma seperated column SQL从子查询中获取一列作为逗号分隔的值 - SQL get a column as comma-seperated values from a subquery 如何使用选择查询在数据库的列中的逗号分隔值之间比较单个值? - How to compare the a single value among the comma seperated values in a column of a database using Select Query? 需要在单列中存储多个用逗号分隔的值 - Need to store multiple values seperated by comma(,) in single column SQL Server:将逗号分隔的单列值拆分为多列 - SQL Server : Split a single column value comma seperated to multiple columns 如何获取以逗号分隔的列名列表,其中列值等于“ True” - How to get comma seperated list of column names where column values are equal to “True” 将每个行列的值连接到字符串中,并在SQL中用逗号分隔 - Concatenate Each Row column values into string with comma seperated in SQL 逗号分隔值到SQL IN STATEMENT - Comma seperated values to SQL IN STATEMENT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM