Showing posts with label By. Show all posts
Showing posts with label By. Show all posts

Thursday, December 18, 2008

Pivot with Connect_By


This is a different version of the pivot that I hadn't seen. I wanted to be able to find it so I listed it here. The original code can be found in an article by Younes Naguib.
Column Name_List Format A100

Select Deptno, 
              -- use the substring to get rid of the initial comma
              ----------------------------------------------------
              Substr(Sys_Connect_By_Path(Ename, ','),2)
              As
       Name_List
  From
      (
       Select Ename,
              Deptno,
              --------------------------------------------------
                    Count(*) Over ( Partition By Deptno )
                    As
              Cnt,
              --------------------------------------------------
                    Row_Number () Over ( Partition By Deptno
                                             Order By Ename  )
                    As
              Seq
         From Emp
      )
 Where Seq = Cnt  -- only pick up the first one
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
      Start With  Seq     = 1
 Connect By Prior Seq + 1 = Seq
        And Prior Deptno  = Deptno; 

(TinyURL: http://tinyurl.com/sql-pivot)