tags:

views:

72

answers:

2

I have one table that has sales records and another table that has additional details on each record. What I need to do is build a query that will query the first table and, for each record, list additional details in a virtual column, like this: "Additional detail #1 for record 1: some additional detail; Additional detail #2 for record 1: more additional details;..." Basically, this column is a concatenation of all additional field record values.

There is no limit on how many additional details (records in the additional details table) one record from the primary table can have.

Do you have any suggestions on how to do this?

+2  A: 

for SQL Server 2005 and up you can use this method

Mladen Prajdic
A: 

In MySQL:

SELECT  s.*,
        GROUP_CONCAT(detail)
FROM    sales s
JOIN    details d
ON      d.sale_id = s.id
GROUP BY
        s.id

In SQL Server:

SELECT  s.*,
        (
        SELECT  CASE WHEN ROW_NUMBER() OVER (ORDER BY sale_id) = 1 THEN ', ' ELSE '' END + detail
        FROM    details d
        WHERE   d.sale_id = s.id
        FOR XML PATH('')
        )
FROM    sales s

In PostgreSQL:

SELECT  s.*,
        ARRAY_TO_STRING (
        ARRAY
        (
        SELECT  detail
        FROM    details d
        WHERE   d.sale_id = s.id
        ), ', ')
        )
FROM    sales s

In Oracle:

WITH q AS (
        SELECT  d.sale_id, d.detail,
                ROW_NUMBER() OVER (PARTITION BY d.sale_id ORDER BY d.detail) AS rn
        FROM    sales s
        JOIN    details d
        ON      d.sale_id = s.id
        )
SELECT  *
FROM    (
        SELECT  *
        FROM    q
        MODEL
        PARTITION BY
                (sale_id)
        DIMENSION BY
                (rn)
        MEASURES
                (detail, detail AS group_concat, 0 AS mark)
        RULES UPDATE (
                group_concat[rn > 1] =  group_concat[CV() - 1] || ', ' || detail[CV()],
                mark[ANY] = PRESENTV(mark[CV() + 1], 0, 1)
                )
        )
WHERE   mark = 1
ORDER BY
        id
Quassnoi
Wow, thanks a bunch. Sorry, I forgot to mention that I use Oracle, but you gave me a hint on where to look for. I'll try with Oracle's wm_concat() which is similar to group_concat().
Dario