sqljoincsvexport

SQL: aggregate a joined table's id's into a string


I need to export data from a SQL database (some groups use SQL Server, some Oracle, etc.) into a CSV where I need the id's from the joined table in a string.

For example, I have a table of Classes and a table of Students. From Classes, I need ID, Name, Section, Time, and from Students I need a string of the ID's of Students in the class. The results would return the columns: id,name,section,time,student_ids. The 'student_ids' column should be a delimited string, such as:

'32,43,53,12,41'

The row output would end up being something like:

"1405,Computer Science,101,12-1:30,'32,43,53,12,41'"

The number of Students per Class is not consistent, there could be one Student, or 20 Students. I thought about using a while loop using SQL Server to obtain this data, or a temp table that aggregates the keys, but I want to know if there is any way using standard SQL to accomplish this, so that the script can be portable.

Notes: I know the output format is not ideal, but the only other option is that we will have to pull a different record for each Class/Student combo, and then will have to aggregate the id's separately.


Solution

  • Different RDBMS have different ways to perform this kind of query.

    If you are using MySQL, you should take a look at the GROUP_CONCAT aggregate function.

    In Firebird, you have the LIST aggregate function.

    If you are using SQL Server, there are some answered questions in SO under the . The usual approach is using the FOR XML PATH construct. A good example is this: SQL Query to get aggregated result in comma seperators along with group by column in SQL Server

    There are a few ways of doing that in Oracle, there's a good article here.