-- 向上递归查询
with deptNameInfo(id,pdeptId,deptName) as (select d1.id,d1.pdeptId,d1.deptName from sys_dept d1 where d1.id = ? union all select PARENT.id,PARENT.pdeptId,PARENT.deptName from deptNameInfo CHILD , sys_dept as PARENT where CHILD.pdeptId=PARENT.id )
select * from deptNameInfo;
-- 行转列
select deptNames from (SELECT replace(replace(xml2clob(xmlagg(xmlelement(NAME a, deptName||','))),'',''),'',' ') as deptNames
FROM deptNameInfo
) where deptNames like '%aaaa%';
-- 向下递归查询
with deptNameInfo(id,pdeptId,deptName) as (select d1.id,d1.pdeptId,d1.deptName from sys_dept d1 where d1.id = ?
union all
select CHILD.id,CHILD.pdeptId,CHILD.deptName from deptNameInfo PARENT , sys_dept as CHILD where CHILD.pdeptId=PARENT.id )
select * from deptNameInfo;
以下转载自夏季微风吹
一. 要想实现ORACLE中 的同样效果(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, [需要拼接的字段名]||','))),'',''),'',' ')
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