SQL query for below scenario

时间:2016-04-04 18:26:07

标签: sql sybase

I have a processDependency table which has thousands of records. Sample records are given below:

Proc DepProc
P1   P2
P2   P3
P3   P4
P4   P5
P6   P7

So when I run the SQL query I should be able to derive below:

  1. P1-P2-P3-P4-P5
  2. P6-P7

    Can anyone help me out with a generic SQL.

1 个答案:

答案 0 :(得分:1)

这不太正确,因为它从Proc

获取所有路径

但你没有说清楚应该先使用哪一个。

无论如何,它应该给你一个想法。

SELECT recurse AS
(
   SELECT Proc AS Start, 
          Proc||COALESCE('-'||DepProc,'') AS PATH, 
          DepProc as Next, 1 as Level
   FROM table

   UNION ALL

   SELECT Start,
          PATH||'-'||t.DepProc,
          t.DepProc as Next,
          Level+1 as Level
   FROM recurse r
   JOIN table t ON r.Next = t.Proc
), recurseWithMax AS
(
   SELECT PATH, Start, MAX(Level) OVER (Partition by Start) as Max, Level
)
SELECT Start, PATH
FROM recurseWithMax
WHERE Level = Max