IBM Mainframe Forum Index
 
Log In
 
IBM Mainframe Forum Index Mainframe: Search IBM Mainframe Forum: FAQ Register
 

concat string across rows in db2


IBM Mainframe Forums -> DB2
Post new topic   Reply to topic
View previous topic :: View next topic  
Author Message
Raghuraman_New

New User


Joined: 03 Oct 2008
Posts: 43
Location: Chennai,India.

PostPosted: Fri Oct 30, 2009 3:06 pm
Reply with quote

I need to concat string across rows of a column in a similar fashion as how aggregate functions work .

For eg :-

TABLE1 :-
Code:
 
   WORD_NUM           WORD
      01               HOW
      01               TO
      01               CONCATENATE
      02               PLEASE
      02               HELP


Ans :-
I expect the follwing rows

01 HOW TO CONCATENATE
02 PLEASE HELP
Back to top
View user's profile Send private message
GuyC

Senior Member


Joined: 11 Aug 2009
Posts: 1281
Location: Belgium

PostPosted: Fri Oct 30, 2009 3:58 pm
Reply with quote

this is the fun way (found all over the internet):
Code:
select wordno,   replace(replace(cast(xml2clob(
         XMLAGG(xmlelement(name "A",strip(wordl)))
        ) as varchar(3000))
      ,'<A>','')
   ,'</A>',';')
from table
group by wordno

It is not very clear, with the same query you could get
01 CONCATENATE HOW TO
02 HELP PLEASE

if your table should be
Code:
 No_sent No_word              xWord
     1         1           HOW
     1         2           TO
     1         3           CONCATENATE
     2         1           PLEASE
     2         2           HELP

you could code some recursive SQL :
Code:
with sentences (no_sent,no_word,xsent) as (
select  no_sent, 1, word from table1
where obid = 1
union all
select  a.no_sent, a.no_word + 1, a.xsent !! ' ' !! b.word from sentences A , table1 B
where a.no_sent = b.no_sent and b.no_word = a.no_word+1
and a.no_word < 10  -- = Maximum to make sure you don't get into a loop
)

select * from sentences a
where no_word = (select max(no_word) from sentences b where a.no_sent = b.no_sent)
Back to top
View user's profile Send private message
View previous topic :: :: View next topic  
Post new topic   Reply to topic View Bookmarks
All times are GMT + 6 Hours
Forum Index -> DB2

 


Similar Topics
Topic Forum Replies
No new posts Replace each space in cobol string wi... COBOL Programming 3
No new posts PARSE Syntax for not fix length word ... JCL & VSAM 7
No new posts To get the count of rows for every 1 ... DB2 3
No new posts Sortjoin and Search for a String and ... DFSORT/ICETOOL 1
No new posts Exclude rows with > than x occurre... DFSORT/ICETOOL 6
Search our Forums:

Back to Top