-3

I have a table that looks like:

Event ID  Name
1         Bob
1         Steve
1         Tom
2         Bob
3         Steve
3         Tom

There are thousands of event IDs, and tens of unique names. I'd like an SQL query to return the following table:

Event ID  Names
1         Bob, Steve, Tom
2         Bob
3         Steve, Tom

I'm looking for an aggregate function like SUM() or AVG() except that it joins strings instead of does mathematics.

EDIT: I'm stuck using MS Access on this one.

EDIT 2: I realize that this would be trivial in a client language, but I'm trying to see if I can get an all-SQL solution.

stepthom
  • 1,432
  • 2
  • 16
  • 27

3 Answers3

0

You don't mention which DBMS you are using but in MySQL it's pretty easy:

SELECT EventId, GROUP_CONCAT(Names)
FROM MyTable
GROUP BY EventId

In SQL Server it's a little trickier. The solution I typically see, requires that you use FOR XML PATH. You can find a good article on how to do this here.

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
0

If you are using SQL server you could do something like this

SQL Fiddle Example

  WITH x AS
    (
      SELECT event_id FROM users
      GROUP BY event_id
    )
    SELECT x.event_id, 
           name = STUFF((SELECT ',' + name
                         FROM users WHERE event_id = x.event_id
                         FOR XML PATH('')), 1, 1, '')
    FROM x
HKImpact
  • 610
  • 1
  • 9
  • 23
0

In PostgreSQL this would be:

select EventId, string_agg(name, ',') as names
from the_table
group by EventId;

If you want the names sorted in the list:

select EventId, string_agg(name, ',' order by name) as names
from the_table
group by EventId