tags:

views:

93

answers:

3

Say we have a table

table posts
+---------+-----------+--------------------------------+
| postId  | title     | status    | bodyText           |
+---------+-----------+--------------------------------+
|   1     | Hello!    | deleted   | A deleted post!    |
|   2     | Hello 2!  | deleted   | Another one!       |
|   3     | New 1     | new       | A new one!         |
|   4     | New 2     | new       | A new one again!   |

Can we, in SQL, retrieve a concatenation of a field across rows, by issuing a single query, not having to do the join up in a loop in our back-end code?

Something like

select title from posts group by status ;

Should give a result like

+---------+--------------------+
| deleted | Hello!, Hello 2!   |
| new     | New 1, New 2       |
+3  A: 

If you use MySQL then you can use GROUP_CONCAT:

SELECT status, GROUP_CONCAT(title)
FROM posts
GROUP BY status
Mark Byers
Oh sweet. This is exactly what I wanted.
bobobobo
+1  A: 

In MySQL:

SELECT  status, GROUP_CONCAT(title SEPARATOR ', ')
FROM    posts
GROUP BY
        status

In PostgreSQL:

SELECT  status,
        ARRAY_TO_STRING(
        ARRAY(
        SELECT  title
        FROM    posts pi
        WHERE   pi.status = po.status
        ))
FROM    posts po
GROUP BY
        status
Quassnoi
A: 

You didn't indicate a particular SQL engine.

In Firebird (from 2.1) you can use the LIST() function. Take a look at: link text

It's an aggregate function to do exactly what you need.

I guess it exists in other engines (LIST in Sybase SQL Anywhere, GROUP_CONCAT in MySQL)

Daniel Luyo