Pivot function in Oracle 10g???

Hello everybody,
at the beginning of the week I had a simple problem (I thought that...), but now after trying and trying, I can't find a solution for it. First of all I'm working on Oracle 10g with the version 10.2.0.4.0. I can't change the version, it's standard in the whole company...
At the beginning I have a table like the following one, but please note, that the compartment, the type and the amount are flexible and can change at any time:
comp type amount
a1 6280 10
a2 6280 20
a2 4810 15
a2 1147 12
a3 6280 33
Now I want the table to look like this:
a1 a2 a3
1147 0 12 0
4810 0 15 0
6280 10 20 33
A simple question in Excel for example, I just use the pivot function and have it fixed within 10seconds. But how can I do sth. like this in Oracle with simple SQL? Or it can be PL/SQL too, cause I will use this in an APEX application.
Can you please give me a hint or a solution? But as stated before a1, a2, a3 are just examples it is possible that tomorrow a4, a5 and so on are coming. If it is necessary I can also create additional tables and views of course!
Thanks for your help!
Regards
hoge

Hi Hoge!
Here is your solution:
SELECT TYPE,
       sum(a1) AS a1,
       sum(a2) AS a2,
       sum(a3) AS a3
  FROM (SELECT TYPE,
               decode(comp, 'a1', amount, 0) AS a1,
               decode(comp, 'a2', amount, 0) AS a2,
               decode(comp, 'a3', amount, 0) AS a3
          FROM test)
  GROUP BY TYPE
  ORDER BY TYPE; And here is my test case setup:
CREATE TABLE test
    (comp VARCHAR2(255),
     TYPE NUMBER,
     amount NUMBER);
INSERT INTO test(comp, TYPE, amount) VALUES('a1', 6280, 10);
INSERT INTO test(comp, TYPE, amount) VALUES('a2', 6280, 20);
INSERT INTO test(comp, TYPE, amount) VALUES('a2', 4810, 15);
INSERT INTO test(comp, TYPE, amount) VALUES('a2', 1147, 12);
INSERT INTO test(comp, TYPE, amount) VALUES('a3', 6280, 33);
commit;Best regards,
Matt

Similar Messages

  • How to find exception occured while using LOGON function in oracle 10g

    Hi,
    I am using LOGON function to login with a different user name in oracle 10g forms.
    LOGON ( User, Pass@tns, FALSE)
    The third parameter is passed as 'FALSE' to avoid the login screen to be opened. If any of the other parameter ( User Name, Password, TNS) is passed wrong, connection is not established but no exception is occurred. The value for 'FORM_FAILURE' is set to 'TRUE'.
    What i need is the ORA error for connection failure. The error message related to user name/password (ORA-01017) or connection identifier (ORA-12155).
    How i can get this error code if connection is failed. Is there any other way to login in oracle forms other than 'LOGON'.
    Habib

    Habib Ahmad wrote:
    Hi,
    I am using LOGON function to login with a different user name in oracle 10g forms.
    LOGON ( User, Pass@tns, FALSE)
    The third parameter is passed as 'FALSE' to avoid the login screen to be opened. If any of the other parameter ( User Name, Password, TNS) is passed wrong, connection is not established but no exception is occurred. The value for 'FORM_FAILURE' is set to 'TRUE'.
    What i need is the ORA error for connection failure. The error message related to user name/password (ORA-01017) or connection identifier (ORA-12155).
    How i can get this error code if connection is failed. Is there any other way to login in oracle forms other than 'LOGON'.As salamu alikum, Habib
    If you pass FALSE in login you can't catch anything. Want to catch the error ?
    Then change
    LOGON ( User, Pass@tns, FALSE)
    to
    LOGON ( User, Pass@tns, TRUE) Now Create On-Error trigger at form level
    and try the following code
    if error_code=01017 then
         message('invalid user name or password');
         message('invalid user name or password');
         raise form_trigger_failure;
    elsif error_code=12154 or error_code=1215 then
         message('invalid connection string');
         message('invalid connection string');
         raise form_trigger_failure;
    end if;Hopes this helps
    If someone's response is helpful or correct, please mark it accordingly.

  • How to trace the flow of plsql procedures/functions in oracle 10g

    Hi All,
    Recently I came to know that there is dbms_hprof PL/SQL built-in package in Oracle 11g which can be used to trace PL/SQL calls in a Hierarchical way. (acts as a PL/SQL Hierarchical Profiler).
    Steps are given in -
    http://www.oracle-base.com/articles/11g/PlsqlHierarchicalProfiler_11gR1.php
    I would like to know whether there is a similar package in Oracle 10g because I want to trace the flow of plsql procedure and function calls in order to generate an output in a hierarchical way (for debug purposes).
    The following example shows the flow of procedure calls when I execute PACKAGE_A.Proceudure_A. I want to generate that kind of an output.
    Ex -
    PACKAGE_A.Proceudure_A
    ----|_PACKAGE_A.Proceudure_B
    ----|------|_PACKAGE_B.Proceudure_C
    ----|_PACKAGE_B.Proceudure_M
    ----|------|_PACKAGE_A.Proceudure_B
    ----|-------------|_PACKAGE_C.Proceudure_C
    ----|_PACKAGE_Z.Proceudure_Z
    If there is no similar package in *10g* I would really appreciate if someone can provide me directions to get the job done using the exsting packages and tables in Oracle 10g. Thanks in advance.
    Edited by: user8326781 on Nov 28, 2008 8:57 PM
    Edited by: user8326781 on Nov 28, 2008 8:58 PM
    Edited by: user8326781 on Nov 29, 2008 12:19 AM

    I am not sure that this would serve the purpose or not but still, I guess its worth to atleast be mentioned,
    http://www.oracle-base.com/articles/9i/DBMS_TRACE.php
    HTH
    Aman....

  • How to disable RECYCLE BIN functionality on Oracle 10g R2

    Hi,
    I installed Oracle 10g R2 in windows 2003, then log in SQL * plus with sys as sysdba, try to use the following command to disable the RECYCLE BIN functionality which is new feature in Oracle 10g R2.
    SQL> alter system set "_RECYCLEBIN"=FALSE SCOPE=BOTH;
    I got the error: illegal option for ALTER SYSTEM
    What do I miss? any comments are appreciative.
    Grace

    SQL> alter system set recyclebin=off;
    System altered.
    SQL> alter system set recyclebin=on;
    System altered.
    SQL>Best regards
    Maxim

  • How can I get an execution plan for a Function in oracle 10g

    Hi
    I have:
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE 10.2.0.4.0 Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    I would like to know if is possible to get an EXECUTION PLAN for a FUNCTION if so, how can I get it ?
    Regards

    You can query the AWR data if your interesting SQL consumes enough resources.
    Here is a SQL*Plus script I call MostCPUIntensiveSQLDuringInterval.sql (nice name eh?)
    You'll need to know the AWR snap_id numbers for the time period of interest, then run it like this to show the top 20 SQLs during the interval:
    @MostCPUIntensiveSQLDuringInterval 20The script outputs a statement to run when you are interested in looking at the plan for an interesting looking statement.
    -- MostCPUintesticeSQLDuringInterval: Report on the top n SQL statements during an AWR snapshot interval.
    -- The top statements are ranked by CPU usage
    col inst_no             format      999 heading 'RAC|Node'
    col sql_id              format a16      heading 'SQL_ID'
    col plan_hash_value     format 999999999999 heading 'Plan|hash_value'
    col parsing_schema_name format a12      heading 'Parsing|Schema'
    col module              format a10      heading 'Module'
    col pct_of_total   format        999.99 heading '% Total'
    col cpu_time       format   999,999,999 heading 'CPU     |Time (ms)'
    col elapsed_time   format   999,999,999 heading 'Elapsed |Time (ms)'
    col lios           format 9,999,999,999 heading 'Logical|Reads'
    col pios           format   999,999,999 heading 'Physical|Reads'
    col execs          format    99,999,999 heading 'Executions'
    col fetches        format    99,999,999 heading 'Fetches'
    col sorts          format       999,999 heading 'Sorts'
    col parse_calls    format       999,999 heading 'Parse|Calls'
    col rows_processed format   999,999,999 heading 'Rows|Processed'
    col iowaits        format   999,999,999,999 heading 'iowaits'
    set lines 195
    set pages 75
    PROMPT Top &&1 SQL statements during interval
    SELECT diff.*
    FROM (SELECT e.instance_number inst_no
                ,e.sql_id
                ,e.plan_hash_value
                ,e.parsing_schema_name
                ,substr(trim(e.module),1,10) module
                ,ratio_to_report(e.cpu_time_total - b.cpu_time_total) over (partition by 1) * 100 pct_of_total
                ,(e.cpu_time_total - b.cpu_time_total)/1000 cpu_time
                ,(e.elapsed_time_total - b.elapsed_time_total)/1000 elapsed_time
                ,e.buffer_gets_total - b.buffer_gets_total lios
                ,e.disk_reads_total - b.disk_reads_total pios
                ,e.executions_total - b.executions_total execs
                ,e.fetches_total - b.fetches_total fetches
                ,e.sorts_total - b.sorts_total sorts
                ,e.parse_calls_total - b.parse_calls_total parse_calls
                ,e.rows_processed_total - b.rows_processed_total rows_processed
    --            ,e.iowait_total - b.iowait_total iowaits
    --            ,e.plsexec_time_total - b.plsexec_time_total plsql_time
          FROM dba_hist_sqlstat b  -- begining snap
              ,dba_hist_sqlstat e  -- ending snap
          WHERE b.sql_id = e.sql_id
          AND   b.dbid   = e.dbid
          AND   b.instance_number = e.instance_number
          and   b.plan_hash_value = e.plan_hash_value
          AND   b.snap_id = &LowSnapID
          AND   e.snap_id = &HighSnapID
          ORDER BY e.cpu_time_total - b.cpu_time_total DESC
         ) diff
    WHERE ROWNUM <=&&1
    set define off
    prompt  to get the text of the SQL run the following:
    prompt  @id2sql &SQL_id
    prompt .
    prompt  to obtain the execution plan for a session run the following:
    prompt  select * from table(DBMS_XPLAN.DISPLAY_AWR('&SQL_ID'));
    prompt  or
    prompt  select * from table(DBMS_XPLAN.DISPLAY_AWR('&SQL_ID',NULL,NULL,'ALL'));
    prompt .
    set define on
    undefine LowSnapID
    undefine HighSnapIDI guess you'll need the companion script id2sql.sql, so here it is:
    set lines 190
    set verify off
    declare
       maxDisplayLine  NUMBER := 150;  --max linesize to display the SQL
       WorkingLine     VARCHAR2(32000);
       CurrentLine     VARCHAR2(64);
       LineBreak       NUMBER;
       cursor ddl_cur is
          select sql_id
            ,sql_text
          from v$sqltext_with_newlines
          where sql_id='&1'
          order by piece
       ddlRec ddl_cur%ROWTYPE;
    begin
       WorkingLine :='.';
       OPEN ddl_cur;
       LOOP
          FETCH ddl_cur INTO ddlRec;
          EXIT WHEN ddl_cur%NOTFOUND;
          IF ddl_cur%ROWCOUNT = 1 THEN
             dbms_output.put_line('.');
             dbms_output.put_line('   sql_id: '||ddlRec.sql_id);
             dbms_output.put_line('.');
             dbms_output.put_line('.');
             dbms_output.put_line('SQL Text');
             dbms_output.put_line('----------------------------------------------------------------');
          END IF;
          CurrentLine := ddlRec.sql_text;
          WHILE LENGTH(CurrentLine) > 1 LOOP
             IF INSTR(CurrentLine,CHR(10)) > 0 THEN -- if the current line has an embeded newline
                WorkingLine := WorkingLine||SUBSTR(CurrentLine,1,INSTR(CurrentLine,CHR(10))-1);  -- append up to new line
                CurrentLine := SUBSTR(CurrentLine,INSTR(CurrentLine,CHR(10))+1);  -- strip off up through new line character
                dbms_output.put_line(WorkingLine);  -- print the WorkingLine
                WorkingLine :='';                   -- reset the working line
             ELSE
                WorkingLine := WorkingLine||CurrentLine;  -- append the current line
                CurrentLine :='';  -- the rest of the line has been processed
                IF LENGTH(WorkingLine) > maxDisplayLine THEN   -- the line is morethan the display limit
                   LineBreak := instr(substr(WorkingLine,1,maxDisplayLine),' ',-1); --find the last space before the display limit
                   IF LineBreak = 0 THEN -- there is no space, so look for a comma instead
                      LineBreak := substr(WorkingLine,instr(substr(WorkingLine,1,maxDisplayLine),',',-1));
                   END IF;
                   IF LineBreak = 0 THEN -- no space or comma, so force the line break at maxDisplayLine
                     LineBreak := maxDisplayLine;
                   END IF;
                   dbms_output.put_line(substr(WorkingLine,1,LineBreak));
                   WorkingLine:=substr(WorkingLine,LineBreak);
                END IF;
             END IF;
          END LOOP;
          --dbms_output.put(ddlRec.sql_text);
       END LOOP;
       dbms_output.put_line(WorkingLine);
       dbms_output.put_line('----------------------------------------------------------------');
       CLOSE ddl_cur;
    END;
    /

  • Java functions with Oracle 10g

    I have browsed through other related message threads on this forum and it seems that the general recommendation is to develop stored procedures and functions using PL/SQL.
    I need to implement a set of functions that perform date related processing and are self contained (no SQL code or calls). For this I could reuse some Java methods that I have successfully used in an Apache Derby database. In this situation what is your experience related to performance of Java functions compared to PL/SQL? Does the effort of rewriting this code in PL/SQL make sense?

    I made some changes on the class posted by to solve the encoding problems with CLOBs.
    So here is the result of my job.
    import java.sql.SQLException;
    import oracle.sql.*;
    import java.io.*;
    import java.util.zip.InflaterInputStream;
    import java.util.zip.DeflaterOutputStream;
    * A simple class for LOB compression and decompression in Oracle Database.
    * Will work in 8i and better.  Use utl_compress from 10g onward.
    public class CompressionUtility {
         private static void pipeStreams( InputStream inStream, OutputStream outStream, int bufferSize) throws IOException {
              //System.out.println("PIPE -");
              byte[] buffer=new byte[bufferSize];
              int cnt;
              while ((cnt=inStream.read(buffer))!=-1) {
                   outStream.write(buffer,0,cnt);
         private static void pipeStreams( Reader inStream, Writer outStream) throws IOException {
              //System.out.println("PIPE Reader-Writer");
              int val = 0;
              while ( (val = inStream.read()) != -1 ) {
                   outStream.write(val);
         private static void pipeStreams( Reader inStream, OutputStream outStream) throws IOException {
              //System.out.println("PIPE Reader-");
              int val = 0;
              while ( (val = inStream.read()) != -1 ) {
                   outStream.write(val);
        private static void pipeStreams( InputStream inStream, Writer outStream) throws IOException {
              System.out.println("PIPE -Writer");
              int val = 0;
              while ( (val=inStream.read()) != -1 ) {
                   outStream.write(val);
    * Compresses the CLOB into BLOB
    * @param clob the source CLOB (plain text)
    * @param blob the target BLOB (will hold compressed binary data) it should be
    * an empty BLOB retrieved for example with dbms_lob.createtemporary(l_blob,true);
    * @throws Exception mostly I/O exception if ever
         public static void compress(CLOB clob, BLOB blob) throws IOException, SQLException {
              //System.out.println("Compressione C->B");
              Reader in=clob.getCharacterStream();
              Writer z=new OutputStreamWriter(new DeflaterOutputStream(blob.getBinaryOutputStream()));
              DeflaterOutputStream z = new DeflaterOutputStream(blob.getBinaryOutputStream());
              int val = 0;
              while ( (val=in.read()) != -1 ) {
                   z.write(val);
              pipeStreams(in, z);
              in.close();
              z.close();
    * Decompresses the BLOB into CLOB
    * @param blob the source BLOB (compressed binary data)
    * @param clob the target CLOB (will hold plain text) it should be an empty CLOB
    * retrieved for example with dbms_lob.createtemporary(l_clob,true);
    * @throws Exception mostly I/O exception if ever
        public static void decompress(BLOB blob, CLOB clob)
          throws IOException, SQLException {
               //System.out.println("Decompressione B->C");
            Writer out=clob.getCharacterOutputStream();
            Reader z=new InputStreamReader(new InflaterInputStream(blob.getBinaryStream()));
              InflaterInputStream z = new InflaterInputStream(blob.getBinaryStream());
            int val = 0;
              while ( (val=z.read()) != -1 ) {
                   out.write(val);
            pipeStreams(z, out);
            z.close();
            out.close();
    * Compresses the BLOB into BLOB
    * @param slob the source BLOB (plain binary data)
    * @param blob the target BLOB (will hold compressed binary data) it should be
    * an empty BLOB retrieved for example with dbms_lob.createtemporary(l_blob,true);
    * @throws Exception mostly I/O exception if ever
        public static void compress(BLOB slob, BLOB blob)
          throws IOException, SQLException {
               //System.out.println("Compressione B->B");
            InputStream in=slob.getBinaryStream();
            DeflaterOutputStream z=new DeflaterOutputStream(blob.getBinaryOutputStream());
            pipeStreams(in, z, blob.getBufferSize());
            in.close();
            z.close();
    * Decompresses the BLOB into CLOB
    * @param blob the source BLOB (compressed binary data)
    * @param slob the target CLOB (will hold plain binary data) it should be an
    * empty CLOB retrieved for example with dbms_lob.createtemporary(l_blob,true);
    * @throws Exception mostly I/O exception if ever
        public static void decompress(BLOB blob, BLOB slob)
          throws IOException, SQLException {
               //System.out.println("Decompressione B->B");
            OutputStream out=slob.getBinaryOutputStream();
            InflaterInputStream z=new InflaterInputStream(blob.getBinaryStream());
            pipeStreams(z, out, blob.getBufferSize());
            z.close();
            out.close();
    }The main problem was with the getAsciiStream() function that has to be replaced by getCharacterStream().

  • How to migrate SQL serveer table-valued functions into Oracle 10g

    hi ,
    i'm trying to migrate from SQL server to Oracle. There are some Table_valued functions ( Function that returns table). while migrating using SQL Developer it uses cursor for every table query. is this is the only solution to migrate functions returning table? This tables contains more than LAKH of records? so if there any other solution on this please reply. the sample code is bellow.
    CREATE function FU_AIG_S_GET_LOG
    returns TABLE
    as
    RETURN     
    SELECT U_AIG.T_AIG_LOG.AIG_LOG_NB_IDLOG,
    U_AIG.T_AIG_LOG.AIG_LOG_NB_EVTSUIVI,
    U_AIG.T_AIG_LOG.AIG_LOG_NB_CODELOG,
    U_AIG.T_AIG_LOG.AIG_LOG_DT_CREATION,
    U_AIG.T_AIG_LOG.AIG_LOG_CL_XMLEVT,
    U_AIG.T_AIG_TYPELOG.AIG_TYPELOG_VC_NOMLOG
    FROM U_AIG.T_AIG_LOG INNER JOIN U_AIG.T_AIG_TYPELOG
              ON U_AIG.T_AIG_LOG.AIG_LOG_NB_CODELOG =
    U_AIG.T_AIG_TYPELOG.AIG_TYPELOG_NB_CODELOG
    WHERE AIG_LOG_NB_LU = 0;
    thanks
    sush
    Message was edited by:
    user610355
    Message was edited by:
    user610355

    I don't think there's good work around over that. Mysql .sql file syntax is a little different from Oracle. Especially the DDLs.
    Unless you are willing to blindly run the .sql file and fix the one failed manually.

  • Equivalent to the Pivot command on Oracle 10g

    Hi,
    I have a requirement where i want change the below statement so it pivots on the day of the week
    select periodid, entrydate, duration
    from period
    where period_id = xxxx
    The above statement will return 7 records for each of the days of the week.
    I want these 7 days to become columns.
    Is there a way I can change this so is it
    select period_id_monday, monday_duration, period_id_tuesday, tuesday_duration,
    period_id_wednesday, wednesday_duration, period_id_thursdayday, thursday_duration,
    period_id_friday, friday_duration
    without having 7 separate sub queries.
    Pivot command in SQL server is only for group functions from what I remember
    Regards
    Stephen

    You could have googled or searched the forums! The method is
    select max(decode(to_char(entrydate, 'fmDAY', 'nls_date_language=english'), 'MONDAY', periodid)) monday_perodid,
           max(decode(to_char(entrydate, 'fmDAY', 'nls_date_language=english'), 'MONDAY', duration)) monday_duration,
    from   perod
    where  period_id = xxxxleaving you to fill in the blanks...
    Edited by: Boneist on 01-Jul-2009 12:01

  • Pivot Query on Oracle 10g

    Table Structure
    GRP_NR Values
    1 A
    1 B
    2 A
    2 B
    2 C
    3 A
    3 B
    3 C
    N A
    N B
    N C
    I would like to convert the above structure into the following. I prefer to have it as sql query, but open to plsql solution too.
    1 2 3 ..................... N
    A A A ..................... A
    B B B ..................... B
    . C C ..................... C
    I am finding it quite a challenge to do it. especially to make it dynamic.
    I will appreciate your help.

    With model clause.
    Regards salim.
    select GRP_NR, substr( string, 2 ) as string
    from t
    model
    return updated rows
    partition by ( GRP_NR )
    dimension by ( row_number() over (partition by GRP_NR ORDER BY val asc) as position )
    measures ( cast( val as varchar2(1000) ) as string )
    rules
    upsert
    iterate(1000 )
    until ( presentv(string[iteration_number+2],1,0) = 0 )
    ( string[0] = string[0] || ',' || string[iteration_number+1] )
    order by GRP_NR ;
    SQL> with t as (
      2  select 1 GRP_NR, 'A' val from dual union all
      3  select 1 ,'B' val from dual union all
      4  select 2 ,'A' val from dual union all
      5  select 2 ,'B' val from dual union all
      6  select 2 ,'C' val from dual union all
      7  select 3 ,'A' val from dual union all
      8  select 3 ,'B' val from dual union all
      9  select 3 ,'C' val from dual )
    10  select GRP_NR, substr( string, 2 ) as string
    11  from t
    12  model
    13  return updated rows
    14  partition by ( GRP_NR )
    15  dimension by ( row_number() over (partition by GRP_NR ORDER BY val asc) as position )
    16  measures ( cast( val as varchar2(1000) ) as string )
    17  rules
    18  upsert
    19  iterate(1000 )
    20  until ( presentv(string[iteration_number+2],1,0) = 0 )
    21  ( string[0] = string[0] || ',' || string[iteration_number+1] )
    22  order by GRP_NR ;
        GRP_NR STRING
             1 A,B
             2 A,B,C
             3 A,B,C
    SQL>

  • Oracle 10g Pivot query

    Hi,
    I want to create a view. Sales amounts, countries and products will be showed in this view.
    Report result will be like below:
    Products
    Countries Sales_Amount
    TV Ipad Iphone Netbook Notebook EbookReader
    England 1000 1200 1400 3000 5000 200
    Germany 800 1000 1300 2800 6000 400
    France 1100 1100 1500 2400 3000 500
    Number of products are not limited. New prodcuts can be added by the time.
    Customer is using Oracle 10g. So I can not use pivot function which cames with Oracle 11g.
    If the number of products is limited, I can write sql by decode operators.
    But I can not find how to implement pivot function in Oracle 10g with unlimited column values.
    Do you have any comment?
    Thanks,Regards

    From the SQL and PL/SQL FAQ:
    "This is not easily possible as the number of columns returned by an SQL must be known before any data is fetched, it would have to be done dynamically.
    See these threads:
    Franks pivoting, static and dynamic
    Dynamic Columns Pipelined"
    SQL and PL/SQL FAQ

  • Pivot in oracle 10g

    Hi Master ,
    Q1>
    I have two column in a table on oracle 10g.
    data like :
    NAME     DATE
    a     10-JAN-13
    a     11-JAN-13
    a     12-JAN-13
    I want the output like :
    NAME     DATE     
    a     10-JAN-13,11-JAN-13,12-JAN-13.
    Q2>
    How can i use pivot in oracle 10g.
    plz. help.

    Ekalabya wrote:
    I want the output like :
    NAME     DATE     
    a     10-JAN-13,11-JAN-13,12-JAN-13.this looks like string concatenation: http://www.oracle-base.com/articles/misc/string-aggregation-techniques.php
    Pivoting in10g: Pivot function in Oracle 10g???

  • APEX 3.2 -ORACLE 10G - PIVOT QUERY

    Hello, i searched around the forum and i cound't find an answer to this specific matter, although i saw some replies that were close...
    i need to creat a form based on a pivot query. but oracle 10g doesn't support that feature so i hope someone can help me.
    my problem is that the number of columns will be variable. here's an example:
    ORIGINAL TABLE
    NAME     KMS     VEHICLE
    Joe     100     AUDI
    Tom     300     VW
    Mark     150     FORD
    Ann     250     FORD
    Joe     200     VW
    Tom     123     AUDI
    Mark     345     AUDI
    Ann     45     VW
    Joe     6     FORD
    Tom     67     FORD
    Mark     46     VW
    Ann     99     AUDI
    DESIRED RESULT
    Joe     Tom     Mark     Ann     Vehicle
    100     123     345     99     AUDI
    6     67     150     250     FORD
    200     300     46     45     VW
    the new columns will be the values in the old NAME column. BUT these values are variable. today its joe,tom,mark and ann tomorrow it could be silvia, tony,richard,harry , william and jane. this means the usuall replies i saw, using MAX and DECODE will not apply because i never know what values or how many values are in this column. with pivot i can get this done.... how can i do this in oracle 10g? is there a way to creat a ser function Pivot somehow? ideas?
    thanks!
    Mark Pereira
    Edited by: 899716 on Jul 18, 2012 12:02 PM

    This is the Oracle Forms forum. Post your question in the SQL forum.
    Tip: check the latest Oracle Magazine (July/August 2012). There is an article by Tom Kyte about the same question.
    http://www.oracle.com/technetwork/oramag/magazine/home/index.html

  • Function not executing in oracle 10g

    Hi ALL,
    I have a problem executing below Function in oracle 10g.
    Pls do help me solve the prblm it wud be a great help.
    Thanks in advance.
    Here is a below function and the error i am getting:
    create or replace FUNCTION UnpackArray
    Source IN VARCHAR2 DEFAULT NULL,
    Delimiter IN CHAR DEFAULT ','
    RETURN reSourceArray0 PIPELINED
    IS
    SourceArray00 SourceArray0:=SourceArray0(NULL);
    TYPE REFCURSOR IS REF CURSOR;
    CURSOR0 REFCURSOR;
    DelLen int;
    Pos int;
    Cnt int;
    str int;
    LEN int;
    Holder VARCHAR2(220);
    BEGIN
    --Check for NULL
    IF Source is null or Delimiter is null THEN
    Return;
    END IF;
    --Check for at leat one entry
    IF RTRIM(LTRIM(Source)) = '' THEN
    Return;
    END IF;
    /*Get the length of the delimeter*/
    SELECT LENGTH(RTRIM(Delimiter)) INTO DelLen FROM DUAL;
    SELECT INSTR(UPPER(Source), UPPER(Delimiter)) INTO Pos FROM DUAL;
    --Only one entry was found
    IF Pos = 0 THEN
    BEGIN
    INSERT INTO UnpackArray_TBL
    ( Data )
    VALUES ( Source );
    return;
    OPEN CURSOR0 FOR SELECT * FROM UnpackArray_TBL;
    END;
    END IF;
    /*More than one entry was found - loop to get all of them*/
    SELECT 1 INTO str FROM DUAL;
    << LABEL4 >>
    WHILE Pos > 0
    LOOP
    BEGIN
    /*Set current entry*/
    SELECT Pos - str INTO len FROM DUAL;
    SELECT SUBSTR(Source, str, len) INTO Holder FROM DUAL;
    /* Update array and counter*/
    /* Update array and counter*/
    INSERT INTO UnpackArray_TBL
    VALUES ( Holder );
    /*Set the new strting position*/
    SELECT Pos + DelLen INTO str FROM DUAL;
    SELECT INSTR(UPPER(Source), UPPER(Delimiter), str) INTO Pos FROM DUAL;
    OPEN CURSOR0 FOR SELECT * FROM UnpackArray_TBL;
    END;
    END LOOP;
    /*Set last entry*/
    SELECT SUBSTR(Source, str, length(RTRIM(Source))) INTO Holder FROM DUAL;
    -- Update array and counter if necessary
    IF length(RTRIM(Holder)) > 0 THEN
    INSERT INTO UnpackArray_TBL
    VALUES ( Holder );
    OPEN CURSOR0 FOR SELECT * FROM UnpackArray_TBL;
    END IF;
    --Return the number of entries found
    Return; LOOP
    FETCH CURSOR0 INTO
    SourceArray00.Data;
    EXIT WHEN CURSOR0%NOTFOUND;
    PIPE ROW(SourceArray00);
    END LOOP;
    CLOSE CURSOR0;
    RETURN;
    END;
    Error is : Compilation failed,line 6 (12:13:25)
    PLS-00201: identifier 'RESOURCEARRAY0' must be declared
    Compilation failed,line 0 (12:13:25)
    PL/SQL: Compilation unit analysis terminated

    user11917384 wrote:
    Error is : Compilation failed,line 6 (12:13:25)
    PLS-00201: identifier 'RESOURCEARRAY0' must be declared
    Compilation failed,line 0 (12:13:25)
    PL/SQL: Compilation unit analysis terminatedHave you created a sql user defined type with name RESOURCEARRAY0...??
    Ravi Kumar

  • PL/SQL Introspection - USER_IDENTIFIERS in Oracle 10g

    USER_IDENTIFIERS is a new view as of 11g that will show profile info about stored PL/SQL. For more info, see Tom Kyte's article here:
    http://www.oracle.com/technology/oramag/oracle/07-nov/o67asktom.html
    I need to replicate part of that functionality in Oracle 10g. Specifically, I need to introspect PL/SQL package bodies and query the starting and ending line numbers for their procedures and functions. Based on a pattern by Nigel Thomas, have constructed the query below. Does anyone have a better way to get that information?
    SELECT package_name, object_name program_unit_name,
           progtype program_unit_type, startline start_line,
           DECODE(endline, startline,
                  pkg_last_line, NVL(endline, pkg_last_line)) end_line 
    FROM   (
           SELECT  arg.package_name, arg.progtype, arg.object_name,
                   pkg_body.line startline,
                   LEAD(pkg_body.line) OVER (ORDER BY arg.package_name,
                           pkg_body.line) endline,
                   ( SELECT MAX(line) FROM user_source
                     WHERE  type = 'PACKAGE BODY'
                     AND name = arg.package_name
                   ) pkg_last_line, text
           FROM    (
                      SELECT   package_name, object_name,
                               DECODE(MIN(position),
                                      0, 'FUNCTION',
                                      'PROCEDURE') progtype
                      FROM     user_arguments
                      WHERE    package_name IS NOT NULL
                      GROUP BY package_name, object_name
                   ) arg,
                      SELECT *
                      FROM user_source
                      WHERE type = 'PACKAGE BODY'
                   )  pkg_body
                   WHERE pkg_body.name = arg.package_name
                   AND
                       -- Remove carraige return and line feeds from end of line
                       -- Match declaration of function or procedure. Pad with a
                       -- space to delimit the program unit name. (Some names start
                       -- with the same characters.)
                       -- Allow program unit to be defined with a trailing space or a (
                       -- Assumption: program unit type (FUNCTION, PROCEDURE) and
                       -- name must be on the same line and must be the first thing
                       -- on the line.
                       LTRIM(REPLACE(REPLACE(REPLACE(UPPER(pkg_body.text),CHR(10),''),
                                  CHR(13),'' ),CHR(9), '' )) ||' ' LIKE
                             arg.progtype || '% ' || arg.object_name || ' %'                           
                       OR
                       LTRIM(REPLACE(REPLACE(REPLACE(UPPER(pkg_body.text),CHR(10),''),
                                  CHR(13),''),CHR(9), ''))  ||' ' LIKE
                             arg.progtype || '% ' || arg.object_name || '(%'                           
                   -- Filter out single line comment lines that contain the program
                   -- unit type and name
                   AND SUBSTR(TRIM(pkg_body.text), 1, 2) != '--'
                   -- Filter out lines like multi-line comments that have the
                   -- program unit type and program unit name on the same line.
                   -- Remove tabs and spaces for the concatenation.
                   AND REPLACE(REPLACE(UPPER(pkg_body.text), ' ', ''), CHR(9), '') 
                         LIKE arg.progtype || arg.object_name || '%'
                   -- Filter out lines that contain PL/SQL statements
                   AND pkg_body.text NOT LIKE '%;%'
    );Thanks,
    Peter

    Additionally, don't rely on implicit type conversions which may give unexpected results depending on your session settings
    DBMS_OUTPUT.PUT_LINE('TODAY IS '||to_char(TODAY, 'DD.MM.YYYY'));

  • Xpath difference between Oracle 10g and Oracle 11g

    All,
    I'm working on moving our existing stored functions from Oracle 10g (10.2.0.4.0) to Oracle 11g (11.2.0.1.0) and so far, everything has worked just fine on Oracle 11g...execpt for one xpath statement.
    The statement below works fine in Oracle 10g (10.2.0.4.0):
    extractValue(inv_dtl_img, '/service//ground/sortKeyCode') AS "srt_key_cd",
    Please note: I need to use the double slash "//" in order to ignore the two different elements in the schema.
    However, in Oracle 11g (11.2.0.1.0), when this statement is executed in the stored function, I get this:
    ERROR at line 1:
    ORA-00932: inconsistent datatypes: expected - got -
    The extractValue command is pulling data out of an XMLType column, and the corresponding XML schema looks like:
    <service>
    <trans>
    <ground>
    <sortKeyCode>
    </sortKeyCode>
    </ground>
    </trans>
    <nontrans>
    <ground minOccurs=0>
    <sortKeyCode>
    </sortKeyCode>
    </ground>
    </nontrans>
    </service>
    Please note: In the XML message, the "trans" and "nontrans" elements are exclusive, so both will never be populated at the same time. A typical XML message would look like this:
    <service><trans><ground><sortKeyCode>3</sortKeyCode></ground></trans></service>
    or this:
    <service><nontrans><ground><sortKeyCode>5</sortKeyCode></ground></nontrans></service>
    In the schema, the sortKeyCode has been defined in both places as "string maxlen=3", so the datatype of that element is exactly the same in both the "trans" and "nontrans" sections of the schema. The only difference in the schema (outside of the trans and nontrans tags) is the fact that the second "ground" tag is defined with a "minOccurs=0". Could Oracle 11g be treating the schema differently than Oracle 10g, resulting in the error?
    Any thoughts would be appreciated.

    The only way to get an quick answer to that one is to file a service request with Oracle support. It could be a bug or a correct change regarding W3C behavior. Despite this, you moving to 11.2, the extract/extractvalue etc propriety Oracle solutions are deprecated from 11.2 and onwards. The more sensible way to move forward, although, I know more work intensive, is to apply the XQuery alternatives like xmlexist, xquery or xmltable functions.
    Moving to EXTRACT is a bad idea, because this alway will be treated as an XML fragment. If you unlucky then Oracle will deal with this in memory via DOM (the standard solution regarding XML parsing if every smart thing within Oracle can not be applied) and this will result in a performance downgrade due to high CPU and Memory consumption/overhead...
    Your pick...

Maybe you are looking for

  • Windows system crash when connecting iPod Nano

    The above is a new development. Have had my 2nd Gen iPod Nano for about 3 months with no hitches. Now, however, my system freezes when connecting my iPod for update. The only new bit of software I have downloaded was virus free (according to Norton)

  • Assigning object of one class to object of another class.

    Hi, How will i assign an object of one class to an object of another class? Ex: ClassX A=some_method(); Now how will I assign the object A of class ClassX to the object 'B' of another class 'ClassY'.

  • Transferring photos on Ipod Photo

    i Have an Ipod Photo 60GB . it all works Ok and i have music and 20,000 Photos stored on it. However i have the following problem. i can synch my photos from My G5 to the ipod and store them ok. but what i want to be able to do is to transfer all my

  • Live meeting v806362.215 won't install with sccm 2012

    I'm trying to install Live Meeting 2007 client v806362.215 under SCCM 2012 application model using the .MSI.  "I get a message that says the installer was interrupted before Microsoft Office Live Meeting 2007 could be installed.  You need to restart

  • Import Settings, Use error correction

    I just read that the "Use error correction when reading Audio CDs" box in iTunes Import Settings should really be on, (even though it's slower). on this page http://www.kenrockwell.com/apple/itunes.htm It's copyright 2006 Is this really the case?