简体   繁体   中英

How to select two row values in a row in DB2

I want to select two row values in a row and concatenated.

id     value
------------
1      abc
1      def
2      ghi
3      jkl
3      mno
3      prs

Result should look like:

id     value
------------
1      abc, def
2      ghi
3      jkl, mno, prs

How can i do that?

The link @Dems posted is functionally identical to your requirements.

However, in case you don't have access to the xml functions, here's a recursive CTE version:

WITH Indexed(id, value, index) 
            as (SELECT id, value, ROW_NUMBER() OVER(PARTITION BY id ORDER BY value)
                FROM ValueTable),
     Concatenated(id, index, concatenated) 
                 as (SELECT id, index, value
                     FROM Indexed
                     WHERE index = 1
                     UNION ALL
                     SELECT a.id, a.index + 1, a.concatenated || ', ' || b.value
                     FROM Concatenated as a
                     JOIN Indexed as b
                     ON b.id = a.id
                     AND b.index = a.index + 1)
SELECT a.id, a.value
FROM Concatenated as a
EXCEPTION JOIN Indexed as b
ON b.id = a.id
AND b.index > a.index

If you have a unique index on the initial table, the Indexed CTE can be replaced with a reference to your original table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM