0

I have a table as below with data:-

Item    COL1    COL2    COL3    COL4    COL5    COL6    ....    COL 30
A       1       1       2       3       4       2       5       2
B       2       6       4       3       5       2       5       1
C       3       4       5       2       2       2       4       2
D       4       5       2       23      45      3       3       3
F       5       3       1       11      23      34      34      1

and need to UNPIVOT depending on the value I give... If I give 4, the table is unpivoted to COL4, If I give 7 the table is unpivoted till 7, making it dynamic. I have written a simple SQL but cant get a way to make it dynamic

   SELECT * FROM (
     WITH
      WIDE AS (
     SELECT
      /*+ PARALLEL(128) */
      ITEM, COL1,  COL2,  COL3,  COL4,  COL5,  COL6, COL7
     FROM TAB
     WHERE ITEM  = 'A'
    )
    SELECT
     /*+ PARALLEL(128) */
     ITEM
    FROM WIDE
   UNPIVOT INCLUDE NULLS
   (QTY FOR SCOL IN
    (COL1,  COL2,  COL3,  COL4, COL5,  COL6,
    COL7
    )
   )
  ); 
Radagast81
  • 2,921
  • 1
  • 7
  • 21

1 Answers1

1

Why don't you unpivot all possible columns and then restrict the dataset with the where clause:

SELECT ITEM, SCOL, QTY 
  FROM WIDE
    UNPIVOT INCLUDE NULLS
      (QTY FOR SCOL IN (COL1, ..., COL 30))
 WHERE TO_NUMBER(SUBSTR(SCOL,4)) <= 7 -- 7 Should be replaced with your parameter
Radagast81
  • 2,921
  • 1
  • 7
  • 21