新進的公司數據庫用DB2, 因為之前一直用ORGCLE,對DB2不太熟悉。 現在記錄一下在DB2中特殊函數的用法。
1.1: SELECT [分組的字段],LISTAGG([需要聚合的字段名], ',') WITHIN GROUP(ORDER BY [排序的字段名]) AS employees
FROM [表名] GROUP BY [分組的字段名] ; --注意:需要DB2 9.7以後的版本才支持, 類似ORACLE的wmsys.wm_concat()
1.2:SELECT [分組的字段名] ,replace(replace(xml2clob(xmlagg(xmlelement(NAME a, [需要拼接的字段名]||','))),'<A>',''),'</A>',' ')
FROM [表名] GROUP BY [分組的字段名]; -- DB2 9.7以前的版本都可以執行, 但是需要支持XML
1.3: WITH T1(A,NUM) AS
(
Select name,ROW_NUMBER() OVER(PARTITION BY tbname ORDER BY tbname) as num
FROM sysibm.syscolumns
where tbname='T_SZPX_YL_GPXXB_TEST'
),
t2(ra,num) as(
Select A as a,NUM FROM T1 Where NUM = 1
UNION all
Select RTRIM(T2.RA)||T1.A,t1.num FROM T1 , T2 Where T1.NUM = T2.NUM + 1)
select ra,num from t2
where t2.num=(select max(num) from t1); -- 1.1 和 1.2 都不行的話只能采用遞歸SQL法了
以上SQL運行後效果如下圖:
聚合前的數據格式:
聚合後的數據格式:
二. 實現 BETWEEN AND 功能,就是要查第5條到第8條數據。
2.1: select * from (select ROW_NUMBER() OVER(ORDER BY [排序的字段]) roolLine,t.* from [表名] t ) where roolLine BETWEEN 5 AND 8