0

I have the a table with the following structure :

path: objectId step timestamp

For example

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

I need to do a query the produce the following result:

ObjectId      steps
 1            IN,OUT
 3            PLACED,OUT

I tried the recursion as the following:

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;

but this query failed due to

The fullselect of the recursive common table expression "DB2INST.TEMP" must be the UNION of two or more fullselects and cannot include column functions, GROUP BY clause, HAVING clause, ORDER BY clause, or an explicit join including an ON clause

could you please advise, how can i fix my query to give the desired output or any other idea more efficient?

mustaccio
  • 18,234
  • 16
  • 48
  • 57
User
  • 573
  • 3
  • 15
  • 28
  • Try removing the superfluous/unnecessary parentheses around the individual select. They are totally useless and might actually be a problem here: `with temp as (select ... union all select ...)` is enough –  Jun 04 '15 at 12:19
  • the same result , and it is useful as i want to get the rows with RN=1 – User Jun 04 '15 at 12:26
  • Is `LISTAGG()` available in your version of DB2? – mustaccio Jun 04 '15 at 13:29
  • What version of DB2 are you on? Disallowing `JOIN`s is extremely strange (every version I've used has allowed). More importantly, it's likely also complaining about the `ORDER BY` in the windowing statement... which is probably also suboptimal as you keep recalculating it. You _might_ be able to make it work better by defining an initial CTE that just calculates the row number, then recursive over that (instead of the initial table). – Clockwork-Muse Jun 05 '15 at 10:59
  • For more information about recursive SQL in DB2 please check this webminar https://www.brighttalk.com/webcast/7637/105565 – AngocA Jun 05 '15 at 14:55

0 Answers0