Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

sql - Listagg alternative in db2

My customer is using db2 database without listagg function, but I need to somehow aggregate the primary key information within one field.

Right now (for Oracle) I am using this as a part of bigger query:

SELECT LISTAGG(COLUMN_NAME || ':' || CONTENT, ',') 
WITHIN GROUP (ORDER BY COLUMN_NAME || ':' || CONTENT) 
FROM TABLE
WHERE ROW_IDENTIFIER_ID = I.REC_ID AND I.TABLE_RESULT_ID = T.REC_ID

It there an alternative way to get result of listagg function in db2 database before DB2 as of version 9.7 Fix Pack 41 ?

Version of my customer's database: Linux - Enterprise server edition 9.7, release number 08060107
I got it by executing these selects:

SELECT * FROM TABLE(SYSPROC.ENV_GET_INST_INFO()) AS SYSTEMINFO;
SELECT * FROM TABLE(SYSPROC.ENV_GET_PROD_INFO()) AS SYSTEMINFO;
SELECT * FROM TABLE(SYSPROC.ENV_GET_SYS_INFO()) AS SYSTEMINFO;

I admit I don't understand, how can it be 9.7, but there is not listagg function?! :confused:

I also did executed:

SELECT * FROM SYSCAT.FUNCTIONS

I got back this function list, but there are no functions like xmltext or xmlgroup mentioned in alternative solutions down in the answers:(. What neanderthal database is the customer using? Or am I missing something?

Thanks for the responses.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If your version of DB2 supports pureXML (that would be at least DB2 for LUW 9.1 and I believe DB2 9 for z/OS), in addition to what @PM77-1 suggested above, you could use the XMLAGG function:

select xmlserialize(
  xmlagg(
    xmlconcat(
      xmltext(column_name),
      xmltext(':'),
      xmltext(content),
      xmltext(',')
    )
  ) as varchar(10000)
) 
from 
  yourtable 
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...