Home > Database > Mysql Tutorial > How to Perform Dynamic Pivots in Oracle SQL with Varying Values?

How to Perform Dynamic Pivots in Oracle SQL with Varying Values?

Susan Sarandon
Release: 2025-01-24 00:57:10
Original
734 people have browsed it

How to Perform Dynamic Pivots in Oracle SQL with Varying Values?

Oracle SQL Dynamic Pivot Table: Coping with Changing Values

Handling dynamic values ​​in IN statements can be tricky when using the PIVOT function in Oracle SQL. This article provides a solution.

Oracle's PIVOT usually requires the use of static value strings in the IN statement, for example:

<code class="language-sql">... pivot (sum(A) for B in (X))  </code>
Copy after login

However, if the value of B is stored in a database column and updated regularly, manually updating the string X becomes impractical.

To solve this problem, we can use a trick which involves creating a IN string and then using it in the PIVOT query. Let’s break it down:

Step 1: Build the IN string

To create a string, we use the COLUMN NEW_VALUE and LISTAGG functions as follows:

<code class="language-sql">COLUMN temp_in_statement new_value str_in_statement
SELECT DISTINCT 
    LISTAGG('''' || myLetter || ''' AS ' || myLetter,',')
        WITHIN GROUP (ORDER BY myLetter) AS temp_in_statement 
    FROM (SELECT DISTINCT myLetter FROM myTable);</code>
Copy after login

This query builds a string similar to:

<code>'A' AS A,'B' AS B,'C' AS C</code>
Copy after login

Step 2: Using strings in PIVOT

Now we can add this string to our PIVOT query:

<code class="language-sql">SELECT * FROM 
    (SELECT myNumber, myLetter, myValue FROM myTable)
    PIVOT (Sum(myValue) AS val FOR myLetter IN (&str_in_statement));</code>
Copy after login

Restrictions:

While this method provides a solution, it has a limitation: the maximum length of the connection string is 4000 bytes. Therefore, this method may not be suitable if the number of values ​​of B is very large.

The above is the detailed content of How to Perform Dynamic Pivots in Oracle SQL with Varying Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template