DB2中的递归SQL

时间:2015-06-04 08:33:41

标签: db2

我有一个具有以下结构的表:

路径: OBJECTID 步 时间戳

例如

objectId    step    timestamp
 1          IN     2014-04-12
 1          OUT    2014-04-13
 3          OUT    2014-04-11
 3          PLACED 2014-04-10

我需要进行查询,产生以下结果:

ObjectId      steps
 1            IN,OUT
 3            PLACED,OUT

我尝试了递归,如下所示:

WITH TEMP(objectId,STEP,RN) AS
(
(   

SELECT * FROM ( 
    SELECT  SCE.objectId
    ,SCE.STEP
    ,ROW_NUMBER() OVER (  PARTITION BY  objectId order by timestamp ) as RN

    FROM KAP.path SCE 
    WHERE   SCE.STEP IN ('IN','PLACED','OUT')
) WHERE RN =1

)
UNION ALL 
(

SELECT * FROM (     
    SELECT SCE1.objectId
    , STEP
    , ROW_NUMBER() OVER (  PARTITION BY  objectId order by timestamp ) as   RN1

    FROM TEMP ,  path SCE1
    WHERE TEMP.objectId = SCE1.objectId
    AND  SCE.STEP IN ('IN','PLACED','OUT')

)WHERE RN +1 = RN1

) 
) select * from TEMP ORDER BY 1;

但由于

,此查询失败
  

全面选择递归公用表表达式" DB2INST.TEMP"必须是两个或更多全选的UNION而不能   包括列函数,GROUP BY子句,HAVING子句,ORDER BY   子句,或包含ON子句的显式连接

请问您能告诉我,我如何修复我的查询以提供所需的输出或任何其他想法更有效?

0 个答案:

没有答案