从逗号分隔的ID获取逗号分隔的文本

时间:2018-12-18 10:31:25

标签: sql oracle csv

我有两个表,tblStudent和tblDepartment。我将DeptIds以逗号分隔值的形式存储在学生表中,例如-

StudentId  DeptIds
1          1,2,3
2          4
3          1,5

我想在学生表的GetById过程中用逗号而不是DeptIds分隔部门名称。有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

首先,更改数据模型,使其不包含DeptIds CSV列值

从您的问题中可以看出,这是非常不切实际的,使用更好的数据模型是永远不会发生的。

我建议使用以下数据模型:

  • tblStudent表具有最少的学生数据(id,姓名,姓氏,出生日期...)
  • tbl部门表,部门数据最少(id,dept_name,dept_group ...)
  • tblStudentDept作为中间表,具有连接数据(StudentId,DeptId,ActivityInd,date_from,date_until ...)

这样,您将使用tblStudentDept表逐行存储有关特定部门中学生角色的数据:

ID  StudentId  DeptIds    
 1   1          1
 2   1          2
 3   1          3   
 4   2          4
 5   3          1
 6   3          5

之后,您可以使用LISTAGG函数显示CSV数据

对于ID,就像以前一样:

WITH AS中带有测试数据示例的代码:

WITH tblStudentDept AS(
    select 1 as id, 1 as StudentID, 1 as DeptID from dual
    union all
    select 2 as id, 1 as StudentID, 2 as DeptID from dual
    union all
    select 3 as id, 1 as StudentID, 3 as DeptID from dual
    union all
    select 4 as id, 2 as StudentID, 4 as DeptID from dual
    union all
    select 5 as id, 3 as StudentID, 1 as DeptID from dual
    union all
    select 6 as id, 3 as StudentID, 5 as DeptID from dual
)
SELECT sd.StudentID, LISTAGG(DeptID, ',') WITHIN GROUP (ORDER BY sd.DeptID)
  FROM tblStudentDept sd
 GROUP BY sd.StudentID;

按部门要求输入部门名称:

使用WITH AS表和希望新建的tblDepartment表之间的连接,在tblStudentDept中包含测试数据示例的代码:

WITH tblStudentDept AS(
    select 1 as id, 1 as StudentID, 1 as DeptID from dual
    union all
    select 2 as id, 1 as StudentID, 2 as DeptID from dual
    union all
    select 3 as id, 1 as StudentID, 3 as DeptID from dual
    union all
    select 4 as id, 2 as StudentID, 4 as DeptID from dual
    union all
    select 5 as id, 3 as StudentID, 1 as DeptID from dual
    union all
    select 6 as id, 3 as StudentID, 5 as DeptID from dual
),
tblDepartment AS(
    select 1 as DeptId, 'Dept-1' as DeptName from dual
    union all
    select 2 as DeptId, 'Dept-2' as DeptName from dual
    union all
    select 3 as DeptId, 'Dept-3' as DeptName from dual
    union all
    select 4 as DeptId, 'Dept-4' as DeptName from dual
    union all
    select 5 as DeptId, 'Dept-5' as DeptName from dual
)
SELECT sd.StudentID, LISTAGG(d.DeptName, ',') WITHIN GROUP (ORDER BY sd.DeptID) as DeptNames
  FROM tblStudentDept sd
  JOIN tblDepartment d
    ON (d.DeptId = sd.DeptId)
 GROUP BY sd.StudentID;

代码输出:

StudentId  DeptNames    
 1          Dept-1,Dept-2,Dept-3
 2          Dept-4
 3          Dept-1,Dept-5

希望我能帮上忙!