Implementing data field splicing in DB2 (LISTAGG() and xml2clob, xmlagg)

1. Use the function LISTAGG()

1.1 Same as Oracle implementation

1.2 Using LISTAGG() in DB2

1.2.1 About DB2 version

  • My version is10.5,After testing, DB2 V9.7.0.10 can also be used (I don’t know about other versions, it seems to be 9.7 and above), if you don’t know your own version, you can use the following sql to check:
    select * from sysibmadm.env_inst_info;
    
    Insert image description here

1.2.2 Data preparation

1.2.3 Code implementation

  • Look at the data in the table SYS_USER first, as follows:
    Insert image description here
  • Splice the names of all developers under 部门D001 into one field, which is actually exactly the same as Oracle, as follows:
    SELECT
    	DEPT_ID ,
    	listagg(su.USER_NAME  ,',') WITHIN GROUP (ORDER BY su.USER_NAME) all_user_names
    FROM
    	SYS_USER su
    WHERE
    	DEPT_ID = 'D001'
    GROUP BY
    	DEPT_ID ;
    
    Insert image description here

2 Solve the problem of excessive length of LISTAGG() in DB2

2.1 Using xmlagg + xmlelement

  • xmlaggThe syntax is as follows:
    xmlagg(xmlelement(NAME [自定义xml标签], '需要拼接的数据')) AS [字段别名]
    
  • xmlelement,xmlelement() is a function that specifies XML elements. This function requires the following two parameters:
    • name: Specifies the name of the generated XML tag element.
    • [Data that needs to be spliced]: The data contained in the element can be one or more values, which can be spliced ​​and separated by custom delimiters.
    • xmlagg()The function will concatenate the results of all XML elements into an XML document in a sequential manner, thereby returning an XML type value.
  • Implementation code:
    SELECT DEPT_ID ,xmlagg(xmlelement(NAME userName, su.USER_NAME||',')) AS all_user_names
    FROM SYS_USER su 
    WHERE DEPT_ID = 'D001'
    GROUP BY DEPT_ID; 
    
    Insert image description here
  • The implementation code (plus sorting) is as follows:
    SELECT DEPT_ID ,xmlagg(
    	xmlelement(NAME userName, su.USER_NAME||',') ORDER BY su.USER_NAME
    ) AS all_user_names
    FROM SYS_USER su 
    WHERE DEPT_ID = 'D001'
    GROUP BY DEPT_ID; 
    

2.2 Remove the xml tag

  • Use replace() function, as follows:
    SELECT [分组的字段名]
    ,replace(replace(xml2clob(xmlagg(xmlelement(NAME a, [需要拼接的字段名]||','))),'<A>',''),'</A>',' ') 
    FROM [表名] GROUP BY [分组的字段名];
    
  • The test code implementation is as follows:
    SELECT DEPT_ID ,
    replace(replace(xml2clob(xmlagg(xmlelement(NAME userName, su.USER_NAME||','))),'<USERNAME>',''),'</USERNAME>',' ') AS all_user_names
    FROM SYS_USER su 
    WHERE DEPT_ID = 'D001'
    GROUP BY DEPT_ID; 
    
    Insert image description here

Guess you like

Origin blog.csdn.net/suixinfeixiangfei/article/details/134529340
db2
db2