Dynamic pivot in oracle sql

后端 未结 7 1085

... pivot (sum(A) for B in (X))

Now B is of datatype varchar2 and X is a string of varchar2 values separated by commas.
Values for X are select distinct values

7条回答
  •  猫巷女王i
    2020-11-22 00:15

    I used the above method (Anton PL/SQL custom function pivot()) and it done the job! As I am not a professional Oracle developer, these are simple steps I've done:

    1) Download the zip package to find pivotFun.sql in there. 2) Run once the pivotFun.sql to create a new function 3) Use the function in normal SQL.

    Just be careful with dynamic columns names. In my environment I found that column name is limited with 30 characters and cannot contain a single quote in it. So, my query is now something like this:

    SELECT 
      *
    FROM   
      table( 
            pivot('
                    SELECT DISTINCT
                        P.proj_id,
                        REPLACE(substr(T.UDF_TYPE_LABEL, 1, 30), '''''''','','') as Attribute,
                        CASE
                          WHEN V.udf_text is null     and V.udf_date is null and      V.udf_number is NOT null  THEN to_char(V.udf_number)
                          WHEN V.udf_text is null     and V.udf_date is NOT null and  V.udf_number is null      THEN to_char(V.udf_date)
                          WHEN V.udf_text is NOT null and V.udf_date is null and      V.udf_number is null      THEN V.udf_text
                          ELSE NULL END
                        AS VALUE
                    FROM
                        project   P
                    LEFT JOIN UDFVALUE V ON P.proj_id     = V.proj_id 
                    LEFT JOIN UDFTYPE  T ON V.UDF_TYPE_ID = T.UDF_TYPE_ID
                    WHERE 
                        P.delete_session_id  IS NULL AND
                        T.TABLE_NAME = ''PROJECT''
        ')
    )
    

    Works well with up to 1m records.

提交回复
热议问题