GeoVIP GeoVIP - 3 months ago 9
SQL Question

How to concate joined table fields for xml

Hi have data structure like this :

CREATE TEMP TABLE test_names (
id serial primary key,
name character varying(50),
age int
);

INSERT INTO test_names(name,age) values ('name1',10),('name2',20);

CREATE TEMP TABLE test_names_details (
id serial primary key,
test_names_id int,
col1 int,
col2 int,
col3 int
);

INSERT INTO test_names_details(test_names_id,col1,col2,col3)
VALUES(1,2,3,4),(1,5,6,7),(1,8,9,10),(2,20,21,22),(2,23,24,25)


Want from this tables select data like xml :

<info>
<maininfo>
<pn name="name">name1</pn>
<age name="age">10</age>
</maininfo>
<data>
<row>
<col1 name="col1">2</col1>
<col2 name="col2">3</col1>
<col3 name="col3">4</col1>
</row>
<row>
<col1 name="col1">5</col1>
<col2 name="col2">6</col1>
<col3 name="col3">7</col1>
</row>
<row>
<col1 name="col1">8</col1>
<col2 name="col2">9</col1>
<col3 name="col3">10</col1>
</row>
</data>

<maininfo>
<pn name="name">name2</pn>
<age name="age">20</age>
</maininfo>
<data>
<row>
<col1 name="col1">20</col1>
<col2 name="col2">21</col1>
<col3 name="col3">22</col1>
</row>
<row>
<col1 name="col1">23</col1>
<col2 name="col2">24</col1>
<col3 name="col3">25</col1>
</row>
</data>

</info>


How to do it ?

Answer

Wrap this in a function and off you go! ;-)

SELECT
'<info>' || 
    string_agg(
    '<maininfo>' ||
        '<pn name="name">' || name || '</pn>' ||
        '<age name="age">' || age || '</age>' ||
    '</maininfo>' ||
    '<data>' ||
        (SELECT
            string_agg(
        '<row>' ||
            '<col name="col1">'||col1||'</col>' ||
            '<col name="col2">'||col2||'</col>' ||
            '<col name="col3">'||col3||'</col>' ||
        '</row>', '')
        FROM test_names_details WHERE test_names_id = test_names.id
        ) ||
    '</data>'
    , '') ||
'</info>'
FROM test_names
Comments