Oracle
 sql >> Base de données >  >> RDS >> Oracle

Comment créer un pivot dynamique dans Oracle PL SQL

Modifiez votre proc comme ci-dessous

          BEGIN
             -- Use another variable and initialize with count(*) from prev_month (say totalCount)
             -- Initialize another counter say curCount = 0
             -- 
             FOR x IN (select time_stamp from prev_month)

             LOOP
                -- increment curCount. If curCount = totalCount 
                -- then use 
                --  l_query := l_query|| REPLACE (' TO_DATE(''$X$'',''yyyymmdd'') as DAY_$X$_TOTAL ','$X$',x.time_stamp);   --your code without comma at the end.
                -- else 
                l_query := l_query|| REPLACE (' TO_DATE(''$X$'',''yyyymmdd'') as DAY_$X$_TOTAL, ','$X$',x.time_stamp);
               -- end if.
             END LOOP;

EDIT :Syntaxe exacte

           BEGIN
                 curCount := 0;
                 SELECT COUNT (*) INTO o_count FROM prev_month; 
                 FOR x IN (select time_stamp from prev_month)

                 LOOP
                    curCount := curCount +1; -- increment curCount. 
                    IF curCount = o_count THEN
                         l_query :=l_query|| REPLACE (' TO_DATE(''$X$'',''yyyymmdd'') as DAY_$X$_TOTAL ','$X$',x.time_stamp); 
                    else 
                         l_query := l_query|| REPLACE (' TO_DATE(''$X$'',''yyyymmdd'') as DAY_$X$_TOTAL, ','$X$',x.time_stamp);
                   end if.
                 END LOOP;