简体   繁体   中英

concat value of multiple rows into one column

SOURCE DATA:

COLA    COLB   COLC
1       BO     AFV
1       BO     AKG
1       BO     UYD
2       BOS    KJHSDKJ
2       BOS    YWI
3       POS    JHSFJH
3       POS    IUXN

My desired result is below:

COLA    COLB    COLC
1       BO      AFV, AKG,UYD
2       BOS     KJHSDKJ,YWI
3       POS     JHSFJH,IUXN

COLA, COLB are the key columns.

Here is a recursive query that will do the job:

WITH RECURSIVE REC_VIEW (COLA, COLB, ROLL_UP, COLC) 
AS
(
SELECT COLA
     , COLB
     , MIN(COLC) (VARCHAR(1000))
     , MIN(COLC)
FROM  your_table
GROUP BY 1,2
UNION ALL
SELECT B.COLA
     , B.COLB
     , B.ROLL_UP || ',' || A.COLC
     , A.COLC
FROM   your_table A 
INNER JOIN REC_VIEW B
ON    A.COLA = B.COLA
  AND A.COLB = B.COLB
  AND A.COLC > B.COLC
)

SELECT COLA, COLB, ROLL_UP as COLC
FROM REC_VIEW

QUALIFY ROW_NUMBER() OVER (PARTITION BY COLA, COLB
                           ORDER BY CHARACTER_LENGTH(ROLL_UP) DESC) = 1

I wish I understood how to format answers better; all my "pretty" spacing has disappeared. Hope this is clear.

Here's a link to a sample.

It has some sample data and an actual query.

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