Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle - SQL to concatenate multiple rows [duplicate]

Let’ say I have a table with 3 columns

   ID INTEGER,
   OFFSET INTEGER,
   STR VARCHAR(50)

Containing values:

ID          OFFSET   STR
1              1              TestSTR1
1              2              TestSTR3
1              3              TestSTR5
2              1              TestSTR4
2              2              TestSTR2
3              1              TestSTR6

I would like to pull the concatenated “STR” for each ID (ordered by OFFSET). So basically, what I want is:

ID           STR
1              TestSTR1TestSTR3TestSTR5
2              TestSTR4TestSTR2
3              TestSTR6

Any thoughts on how would you construct a similar query?

like image 647
Sachin Kulkarni Avatar asked Oct 28 '25 11:10

Sachin Kulkarni


1 Answers

If you have Oracle 11g you could use the LISTAGG() function for this:

SELECT
      id
    , listagg(str) WITHIN GROUP (ORDER BY OFFSET) AS str_of_str
FROM yourtable
GROUP BY id

see: http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions089.htm and this sqlfiddle

  | ID |               STR_OF_STR |
    |----|--------------------------|
    |  1 | TestSTR1TestSTR3TestSTR5 |
    |  2 |         TestSTR4TestSTR2 |
    |  3 |                 TestSTR6 |
like image 191
Paul Maxwell Avatar answered Oct 31 '25 03:10

Paul Maxwell