SQL - UNPIVOT

Hello All,
I'm trying to get unpivot and pivot to work and can't quite wrap my head around it.
I created a test table which contains DAY, TYPE, DB_ID. In short the backup schedule for a database instance.
Here is my SQL and output.
select b.day_abbrev, c.bck_type_abbrev
from ori_bck_schedules a
left join ori_days b on b.day_id = a.day_id
left join ori_bck_types c on c.bck_type_id = a.bck_type_id
left join ori_databases d on d.database_id = a.database_id
where a.database_id = 369;
DAY_ABBREV BCK_TYPE_ABBREV
SUN        FULL           
MON        INCR           
TUE        INCR           
WED        INCR           
THU        INCR           
FRI        INCR           
SAT        FULL            I would like to unpivot this table to get 1 rows showing the day of the weekend and the type of backup? And I ultimately would like to have 1 row showing the day of the week and then just rows showing the DB_ID.
Here is what I mean:
            SUN     MON  TUE    WED 
DB1      FULL    FULL   INCR
DB2      INCR    INCR   FULL
DB3 ......The below code is not working for me.
select b.day_abbrev as "day", c.bck_type_abbrev as "type"
from ori_bck_schedules a
left join ori_days b on b.day_id = a.day_id
left join ori_bck_types c on c.bck_type_id = a.bck_type_id
left join ori_databases d on d.database_id = a.database_id
unpivot (a for day_abbrev in (b.day_abbrev as 'D',c. bck_type_abbrev as 'T'))
ORA-01748: only simple column names allowed here
01748. 00000 -  "only simple column names allowed here"
*Cause:   
*Action:
Error at Line: 45 Column: 31Can anybody help? Thanks in advance for any assistance
Jan

try like this. if you are on 11g
SQL> WITH T
  2       AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
  3             FROM DUAL
  4           CONNECT BY LEVEL <= 7)
  5  SELECT *
  6    FROM T;
        ID DAY    EXPENSE
         1 SUN         10
         1 MON         20
         1 TUE         30
         1 WED         40
         1 THU         50
         1 FRI         60
         1 SAT         70
7 rows selected.
SQL> WITH T
  2       AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
  3             FROM DUAL
  4           CONNECT BY LEVEL <= 7)
  5  SELECT *
  6    FROM T PIVOT (MAX (expense)
  7           FOR day_of_week
  8           IN ('SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'));
        ID      'SUN'      'MON'      'TUE'      'WED'      'THU'      'FRI'      'SAT'
         1         10         20         30         40         50         60         70
SQL> on 10g
SQL> WITH T
  2       AS (SELECT 1 ID, TO_CHAR ( (SYSDATE - 6) + LEVEL, 'DY') day_of_week, 10 * LEVEL expense
  3             FROM DUAL
  4           CONNECT BY LEVEL <= 7)
  5  SELECT ID,
  6         MAX (DECODE (day_of_week, 'SUN', expense)) AS sun,
  7         MAX (DECODE (day_of_week, 'MON', expense)) AS mon,
  8         MAX (DECODE (day_of_week, 'TUE', expense)) AS tue,
  9         MAX (DECODE (day_of_week, 'WED', expense)) AS wed,
10         MAX (DECODE (day_of_week, 'THU', expense)) AS thu,
11         MAX (DECODE (day_of_week, 'FRI', expense)) AS fri,
12         MAX (DECODE (day_of_week, 'SAT', expense)) AS sat
13    FROM T
14  GROUP BY ID;
        ID        SUN        MON        TUE        WED        THU        FRI        SAT
         1         10         20         30         40         50         60         70
SQL> G.

Similar Messages

  • How to unpivot in SQL Server 2008 R2

    Hi,
    I have data like below:
    AvgPetrolPrice
    AvgKerosenePrice
    AvgGasOilPrice
    GrowthRatePetrol
    GrowthRateKerosene
    GrowthRateGasOil
    685
    689
    688
    0.21
    0.21
    0.21
    I need output like below:
    Product
    Avg for the Year
    Growth Rate for the Year
    Petrol
    685
    0.21
    Kerosene
    689
    0.21
    Gas Oil
    688
    0.21
    Please help ASAP.
    Regards,
    Srini

    See example
    DECLARE @Table TABLE
    UserId INT,
    Day1 INT NULL,
    Day2 INT NULL,
    Day3 INT NULL,
    Day4 INt NULL,
    DayMax Int NULL
    INSERT INTO @Table(UserId, Day1, Day2, Day3, Day4, DayMax)
    VALUES(1,10,null,20,3,null);
    INSERT INTO @Table(UserId, Day1, Day2, Day3, Day4, DayMax)
    VALUES(2,50,25,15,5,null);
    SELECT UserId, DayQuantity AS DayMax FROM @Table
    UNPIVOT (DayQuantity FOR DayNumber IN (Day1,Day2,Day3,Day4)) AS c
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How to Unpivot, Crosstab, or Pivot using Oracle 9i with PL/SQL?

    How to Unpivot, Crosstab, or Pivot using Oracle 9i with PL/SQL?
    Here is a fictional sample layout of the data I have from My_Source_Query:
    Customer | VIN | Year | Make | Odometer | ... followed by 350 more columns/fields
    123 | 321XYZ | 2012 | Honda | 1900 |
    123 | 432ABC | 2012 | Toyota | 2300 |
    456 | 999PDQ | 2000 | Ford | 45586 |
    876 | 888QWE | 2010 | Mercedes | 38332 |
    ... followed by up to 25 more rows of data from this query.
    The exact number of records returned by My_Source_Query is unknown ahead of time, but should be less than 25 even under extreme situations.
    Here is how I would like the data to be:
    Column1 |Column2 |Column3 |Column4 |Column5 |
    Customer | 123 | 123 | 456 | 876 |
    VIN | 321XYZ | 432ABC | 999PDQ | 888QWE |
    Year | 2012 | 2012 | 2000 | 2010 |
    Make | Honda | Toyota | Ford | Mercedes|
    Odometer | 1900 | 2300 | 45586 | 38332 |
    ... followed by 350 more rows with the names of the columns/fields from the My_Source_Query.
    From reading and trying many, many, many of the posting on this topic I understand that the unknown number or rows in My_Source_Query can be a problem and have considered working with one row at a time until each row has been converted to a column.
    If possible I'd like to find a way of doing this conversion from rows to columns using a query instead of scripts if that is possible. I am a novice at this so any help is welcome.
    This is a repost. I originally posted this question to the wrong forum. Sorry about that.

    The permission level that I have in the Oracle environment is 'read only'. This is also be the permission level of the users of the query I am trying to build.
    As requested, here is the 'create' SQL to build a simple table that has the type of data I am working with.
    My real select query will have more than 350 columns and the rows returned will be 25 rows of less, but for now I am prototyping with just seven columns that have the different data types noted in my sample data.
    NOTE: This SQL has been written and tested in MS Access since I do not have permission to create and populate a table in the Oracle environment and ODBC connections are not allowed.
    CREATE TABLE tbl_MyDataSource
    (Customer char(50),
    VIN char(50),
    Year char(50),
    Make char(50),
    Odometer long,
    InvDate date,
    Amount currency)
    Here is the 'insert into' to populate the tbl_MyDataSource table with four sample records.
    INSERT INTO tbl_MyDataSource ( Customer, VIN, [Year], Make, Odometer, InvDate, Amount )
    SELECT "123", "321XYZ", "2012", "Honda", "1900", "2/15/2012", "987";
    INSERT INTO tbl_MyDataSource ( Customer, VIN, [Year], Make, Odometer, InvDate, Amount )
    VALUES ("123", "432ABC", "2012", "Toyota", "2300", "1/10/2012", "6546");
    INSERT INTO tbl_MyDataSource ( Customer, VIN, [Year], Make, Odometer, InvDate, Amount )
    VALUES ("456", "999PDQ", "2000", "Ford", "45586", "4/25/2002", "456");
    INSERT INTO tbl_MyDataSource ( Customer, VIN, [Year], Make, Odometer, InvDate, Amount )
    VALUES ("876", "888QWE", "2010", "Mercedes", "38332", "10/13/2010", "15973");
    Which should produce a table containing these columns with these values:
    tbl_MyDataSource:
    Customer     VIN     Year     Make     Odometer     InvDate          Amount
    123 | 321XYZ | 2012 | Honda      | 1900          | 2/15/2012     | 987.00
    123 | 432ABC | 2012 | Toyota | 2300 | 1/10/2012     | 6,546.00
    456 | 999PDQ | 2000 | Ford     | 45586          | 4/25/2002     | 456.00
    876 | 888QWE | 2010 | Mercedes | 38332          | 10/13/2010     | 15,973.00
    The desired result is to use Oracle 9i to convert the columns into rows using sql without using any scripts if possible.
    qsel_MyResults:
    Column1          Column2          Column3          Column4          Column5
    Customer | 123 | 123 | 456 | 876
    VIN | 321XYZ | 432ABC | 999PDQ | 888QWE
    Year | 2012 | 2012 | 2000 | 2010
    Make | Honda | Toyota | Ford | Mercedes
    Odometer | 1900 | 2300 | 45586 | 38332
    InvDate | 2/15/2012 | 1/10/2012 | 4/25/2002 | 10/13/2010
    Amount | 987.00 | 6,546.00 | 456.00 | 15,973.00
    The syntax in SQL is something I am not yet sure of.
    You said:
    >
    "Don't use the same name or alias for two different things. if you have a table called t, then don't use t as an alais for an in-line view. Pick a different name, like ordered_t, instead.">
    but I'm not clear on which part of the SQL you are suggesting I change. The code I posted is something I pieced together from some of the other postings and is not something I full understand the syntax of.
    Here is my latest (failed) attempt at this.
    select *
      from (select * from tbl_MyDataSource) t;
    with data as
    (select rownum rnum, t.* from (select * from t order by c1) ordered_t), -- changed 't' to 'ordered_t'
    rows_to_have as
    (select level rr from dual connect by level <= 7 -- number of columns in T
    select rnum,
           max(decode(rr, 1, c1)),
           max(decode(rr, 2, c2)),
           max(decode(rr, 3, c3)),
           max(decode(rr, 4, c3)),      
           max(decode(rr, 5, c3)),      
           max(decode(rr, 6, c3)),      
           max(decode(rr, 7, c3)),       
      from data, rows_to_have
    group by rnumIn the above code the "select * from tbl_MyDataSource" is a place holder for my select query which runs without error and has these exact number of fields and data types as order shown in the tbl_MyDataSource above.
    This code produces the error 'ORA-00936: missing expression'. The error appears to be starting with the 'with data as' line if I am reading my PL/Sql window correctly. Everything above that row runs without error.
    Thank you for your great patients and for sharing your considerable depth of knowledge. Any help is gratefully welcomed.

  • Using the Unpivot Operator when in Oracle8i PL/SQL Generation Mode

    Hi,
    when you are validating a mapping with contains an unpivot operator and the PL/SQL Generation Mode is set to Oracle8i (because you're using an Oracle8i 8.1.7. target database) the following error is raised:
    VLD-3127: Cannot generate code for UNPIVOT because the unpivot operator is only supported starting with the Oracle9i version of the database.","The unpivot operator is only supported starting with the Oracle9i version of the database. To resolve this, set the PL/SQL Generation Mode to Oracle9i in the configuration of the Oracle module that contains this mapping.
    When you set the PL/SQL Generation Mode to Oracle9i and after successfully validating the mapping generate the code you can see that within the generated code case-statements are used for the unpivot translation.
    like:
    MIN(CASE WHEN "AGG_YEAR_MONTH" = 200301 THEN "NO_CALLS" ELSE NULL END) "JAN2003_CALLS"
    And as Oracle8i doesn't support the case-statement, the raised validation error is understandable. But the generated code can be easily modified using decode-classes instead of the case-statements.
    results in:
    MIN(DECODE("AGG_YEAR_MONTH",''200301'',"NO_CALLS",NULL)) "JAN2003_CALLS"
    And the generated code works fine in the Oracle8i 8.1.7 target database.
    But now my question:
    Does someone know if it is possible to create a custom unpivot operator in OWB9.2.0 which will generate the code using the decode-class instead of using the case-statements. And if so, how I can create such custom operator.
    Many Thx in advantage!
    Remco

    Hi,
    The reason why OWB does not generate decode statements is that the generated code needs to support both set-based and row-based operation modes. Decodes are valid in SQL (set based), but not in PL/SQL (row based)
    Oracle 8i (8.1.7) does in fact support CASE, but only in SQL statements, not PL/SQL
    Have you considered creating a view to perform the unpivot operation using decode? It should also be possible solve your problem using a function
    Regards,
    Roald

  • Use Pivot & Unpivot in SQL

    Dear All,
    I have a data under Table in below shape..
    1 - means this user is setup on that feature, & 0 means not.
    But, I want to see this output in that way..
    Means - If
    multiple e-mails are configure on same feature, it should come with semi colon in pivot mode..
    Pls Help..

    Look at example 4 in the following blog:
    http://www.sqlusa.com/bestpractices/training/scripts/commadelimitedlist/
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Unpivot or pivot SQL

    I have some tables, only one row, but many columns, like this:
    Name Null? Type
    column1 NUMBER
    column2 VARCHAR2(9)
    column3 VARCHAR2(9)
    column99 VARCHAR2(9)
    I want a SQL to generate this kind of result:
    Column1 : 1
    Column2 : Oracle
    Column3 : DB2
    Column99 : SQL Server
    This SQL could run in 8i,9i,10g and 11g.
    Thanks,

    In asktom you can search for a function called PRINT_TABLE. I have modified a little to use it as a table function.
    drop type table_object
    drop type column_object
    drop function print_table
    create type column_object as object(column_name varchar2(30), column_values varchar2(4000))
    create type table_object as table of column_object
    create or replace function print_table( p_query in varchar2 ) return table_object pipelined
    is
        l_theCursor     integer default dbms_sql.open_cursor;
        l_columnValue   varchar2(4000);
        l_status        integer;
        l_descTbl       dbms_sql.desc_tab;
        l_colCnt        number;
    begin
        execute immediate 'alter session set nls_date_format=''dd-mon-yyyy hh24:mi:ss'' ';
        dbms_sql.parse(  l_theCursor,  p_query, dbms_sql.native );
        dbms_sql.describe_columns( l_theCursor, l_colCnt, l_descTbl );
        for i in 1 .. l_colCnt loop
            dbms_sql.define_column(l_theCursor, i, l_columnValue, 4000);
        end loop;
        l_status := dbms_sql.execute(l_theCursor);
        while ( dbms_sql.fetch_rows(l_theCursor) > 0 ) loop
            for i in 1 .. l_colCnt loop
                dbms_sql.column_value ( l_theCursor, i, l_columnValue );
                pipe row (column_object(l_descTbl(i).col_name,l_columnValue));
            end loop;
        end loop;
        execute immediate 'alter session set nls_date_format=''dd-MON-rr'' ';
        return;
    exception
        when others then
          execute immediate 'alter session set nls_date_format=''dd-MON-rr'' ';
          raise;
    end;
    show errSo this would work like this.
    SQL> select * from table(print_table('select * from emp'))
      2  /
    COLUMN_NAME                    COLUMN_VALUES
    EMPNO                          1
    DEPTNO                         1
    ENAME                          Karthick
    SAL                            80
    DOJ                            03-dec-2011 04:31:17
    JOB
    MGR
    EMPNO                          2
    DEPTNO                         1
    ENAME                          Karthick_1
    SAL                            90
    DOJ                            23-nov-2011 04:31:17
    JOB
    MGR                            1
    EMPNO                          3
    DEPTNO                         2
    ENAME                          1
    SAL                            80
    DOJ                            03-dec-2011 04:31:17
    JOB
    MGR
    EMPNO                          4
    DEPTNO                         2
    ENAME                          Ram_1
    SAL                            90
    DOJ                            23-nov-2011 04:31:17
    JOB
    MGR                            3
    28 rows selected.
    SQL>
    This SQL could run in 8i,9i,10g and 11g.Oh boy i cant say that :)

  • Unpivot task is generating rows for null inputs

    So I have a C# application (VS 2012 with .NET4.5) that builds SSIS (SQL2012) packages programatically.  the packages can be opened in the designer and they run fine.  However, there is one case that is giving me a problem.  I have an
    OleDb source connected to a table in SQL server.  I am using the unpivot task to convert columns in a sparse matrix to an Entity Attribute Value model.  So basically, the primary key value of the source table is a pass-through value in the unpivot
    task, each column is mapped to the destination column, and the attribute id is hard coded as the pivot key.  Like i said this works great EXCEPT i came across one column and a table that was null for all the rows in the table.  when I run the package,
    it fails with:
    OnError,SERVERNAME,DOMAIN\user,{94E83A3B-5386-4712-BEDC-11E35341675F},{94E83A3B-5386-4712-BEDC-11E35341675F},{3187347C-8D44-4D51-8FDB-B5C4159A58B0},9/14/2012 9:48:02 AM,9/14/2012 9:48:02 AM,-1071607780,0x,There was an error with OLE DB Destination.Inputs[OLE
    DB Destination Input].Columns[AttributeId] on OLE DB Destination.Inputs[OLE DB Destination Input]. The column status returned was: "The value violated the integrity constraints for the column."
    So I set up a data viewer on the data flow and found that the unpivot component was generating rows for every null value. not only that, but the values for the key column and the attribute id (which was hard coded) were also null for all the rows
    sent from the unpivot to the ole db destination.  I manually created a package with an unpivot for just the column in question and got the same result.  then I inserted a value for every row in the table and the same package runs fine.
    can someone offer any help or advice on what might be causing this?

    its just two columns of data that are concerned.  ten character numeric strings in the one and null in the other.  the pivot key is hard coded in the unpivot component configuration screen.  see the output of the data viewer below. How do
    I get Microsoft involved with this?
    2013399057 NULL
    2013399488 NULL
    2013399770 NULL
    2013402244 NULL
    2013402440 NULL
    2013404066 NULL
    2013404070 NULL
    2013404203 NULL
    2013404206 NULL
    2013404401 NULL
    2013404589 NULL
    2013404705 NULL
    2013404738 NULL
    2013404768 NULL
    2013404784 NULL
    2013404813 NULL

  • Unpivot multiple products fields data dynamically

    Hi,
    I am having data as below;
       ID
          CMC
          EMS   
            KBP
    Week1
    501378
    320967
    822.54
    Week2
    13500
    6000
    3000
    Week3
    34534
    63563
    9868
    Week4
    32523
    32532
    54223
    Week5
    235235
    53453
    34534
    Week6
    34534
    534534
    34534
    I want to show the above data like below;
    Product
        Week1
         Week2
        Week3
        Week4
        Week5
        Week6
    CMC
    501378
    13500
    34534
    32523
    235235
    34534
    EMS
    320967
    6000
    63563
    32532
    53453
    534534
    KBP
    822.54
    3000
    9868
    54223
    34534
    34534
    I tried the following query: 
    declare @ListWeekData varchar(max)
    declare @query nvarchar(max)
    SET @ListWeekData = STUFF((SELECT distinct ',' + QUOTENAME(convert(varchar,WeekOfMonth))   
                FROM  #WeeklyBreakupData
                FOR XML PATH(''), TYPE  
                ).value('.', 'NVARCHAR(MAX)')   
            ,1,1,'') 
    print @ListWeekData
    SELECT @query = 'SELECT Product
      FROM 
      #WeeklyBreakupData
      UNPIVOT
        Producta FOR Product IN (' + STUFF(@ListWeekData, 1, 1, '') + ')
      ) AS up;';
    PRINT @query;
     EXEC (@query);
    drop table #WeeklyBreakupData
    but unable to get the desired result. Please help me out ASAP.
    Thanks,
    Srini

    Here you go
    CREATE TABLE tmp (Name CHAR(1),Forecast INT,Stock INT)
    INSERT tmp SELECT 'a',100,300  
    INSERT tmp SELECT 'b',300,400 
    INSERT tmp SELECT 'c',200,250
    INSERT tmp SELECT 'd',200,300
    -- dynamic pivot (SQL Server 2005/2008)
    DECLARE @pivot_cols NVARCHAR(1000);
    SELECT @pivot_cols =
            STUFF((SELECT DISTINCT '],[' + Name
                   FROM tmp
                   ORDER BY '],[' + Name
                   FOR XML PATH('')
                   ), 1, 2, '') + ']';
    DECLARE @pivot_query NVARCHAR(2000);
    SET @pivot_query =
    N'SELECT * FROM (
    SELECT * FROM (
    SELECT Name,SUM(Forecast) Forecast,SUM(Stock) Stock FROM tmp
    GROUP BY Name ) tmp UNPIVOT
     Col for [GROUP] IN (Forecast,Stock)
    ) as UnPvt ) pvt
    PIVOT (MAX(Col) FOR Name IN (' + @pivot_cols + ')) j'
    EXEC(@pivot_query);
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • To use SQL or to not use SQL ..... That is the question

    A couple of posts lately have brought something to my attention that I wanted to discuss between the folks that view this forum because I believe it is important. I highly value the opinions of many of the members here so I think getting your insight would not only benefit me, but many other forum members as well.
    This discussion stems from two posts:
    {message:id=3786432} (Billy)
    ...The question that you need to ask yourself is why use such a technique? For rendering the data a specific way in the client? Well, rendering data is NOT a SQL function and in essence a result of ignorance of how to correctly use client-server. Rendering on the client is dealt with by the client itself. Using SQL to do it.. not only nasty (as many of these examples above are), but also far from optimal and efficient SQL. And in most cases, will not scale. Increase the data volume of the table queried and there will be a hefty performance knock as SQL is incorrectly used.
    ...>
    {message:id=3914362} (Sven W.)
    ...For the Pivot considerations. It is usually much better not to try to do this inside the database. If you think about it. The data itself can be fetch from the database very easily. To do a PIVOT is a kind of GUI/Layout representation for this data. This should be done in the GUI Layer.
    >
    I tried to respond to the thread Billy posted in, so I'll cut and paste my response here:
    Discussion
    Where do we as database developers draw the line between the correct use of SQL or not? Or between rendering on the client and just returning data?
    Now with LISTAGG, PIVOT and UNPIVOT all available to us would these be considered correct uses of SQL?
    Where does this leave the TO_CHAR function? Is this considered rendering?
    I'm fully expecting a fuzzy answer with something along the lines of "do the work where it makes the most sense" from a ease of development and maintainability perspective but I just wanted to ask.
    Hopefully this is a valuable discussion.
    Thanks!

    Let me give a simple example. You can store images in a table as a LOB. You can serve these images to a web browser client via mod_plsql.
    However, the data is static. It requires I/O (and some hefty ones for larger images). What is the biggest performance penalty we have in Oracle? I/O? What is affected by doing I/O to read these images? The buffer cache (which will age out other data in the cache).
    Where else can we store this data? The web server. At what cost to the performance of Oracle? None. Impact on web server? Heck, web servers are designed at their very core to do this!
    So where is the best place to storage static images in this specific case? Not the database, but the web server.
    Now simply extend this concept to the client - where is the best place to render data?
    Should the data be formatted for rendering (e.g. converted into HTML) in the database layer, or should it rather be done in the presentation layer?
    Now I can already hear the argument that the former is exactly what we are doing using APEX. We create dynamic HTML pages on the Oracle server side and then dish that up to the rendering layer to display.
    Two issues that need to be considered. Firstly, this is not done using SQL. This is done using a procedure language called PL/SQL - not using native SQL. PL/SQL in this case is used exactly as Java or PHP or Perl or any other "+app layer+" language would be used. It only happens that PL/SQL resides in the database too. But do not mistake it for what it really is - the application layer.
    The second issue drives home the point that even in 3 tier client server, the application layer is not the best place to do the formatting for the rendering layer. Web 2.0 aka AJAX.. Where the app layer delivers a dynamic rendering engine (as Javascript) to the rendering layer. After which rendering and formatting are done solely inside that rendering layer. And interaction between that and the app layer is requests for new/fresh data to be rendered.
    Why is AJAX becoming so popular? Key issues and concepts like performance, and a rich client interface and so on.
    This all points that the fundamental principle of using the rendering layer to do its thing and using the SQL layer to do its (separate and different) thing, still holds true.
    Yes, we may not always stick to this principle - as we do with doing the rendering (creating HTML) in PL/SQL using APEX for example.. but this is not because the principle is unsound. It is because of technology reasons (different browsers, different behaviour), lack of support for W3C standards (hello IE) and so on.
    It is only recently that these problem areas have been meaningfully addressed.. and why rendering frameworks like extJS is the (rendering layer) future of 3 tier client server.
    If the concept of using SQL to perform rendering and formatting had any substance.. then there would have been a lot of resistance to AJAX for example. The reverse is true.. as we all want to use SQL to do SQL and want the rendering layer to do its thing without us having to code in SQL to specifically support rendering and formatting. It is clunky. It slows down the SQL (every formatting function is a tiny overhead that adds up). It does not bode well for maintenance and changes to the presentation layer. And all those tiny overheads can spell doom for scalability.
    I do not see any gray lines here, or a question of "+opinion+", or "+it depends+". The architecture is clear. The fundamentals are sound.
    The real issue is how we choose to apply these. But (the "+incorrect+") application (of these fundamentals) does not invalidate the fundamentals.

  • Lookup creation and using this lookup in SQL query

    I Have two tables one table called T_KEY_VALUES (KEY_ID , VALUE) and other is my transition table T_TRANSACTIONS (VERSION_ID , COL_VENDOR , COL_PREFIX, COL_RECIPTID , COL_STATE , COL_COUNTRY ..)
    The data looks like below:
    T_KEY_VALUES:
    KEY_ID , VALUE,
    10, CA
    11, NY
    13, NJ
    20, USA
    21, CANADA
    101 , AMC
    102, REGAL
    1001, MOVIES
    1002, MALLS
    T_TRANSACTIONS:
    VERSION_ID , COL_VENDOR , COL_PREFIX , COL_RECIPTID , COL_SATE , COL_COUNTRY
    1, 101 , 1001 , 100001 , 10 , 20
    2, 102 , 1002  , 100002 , 11 ,20
    Generally, COL_VENDOR, COL_PREFIX , COL_STATE , COL_COUTRY field values exist in the T_KEY_VALUES table.
    So How can I use T_KEY_VALUES as Lookup and write the one SQL query to get the data like below:
    1, AMC , MOVIES , 100001 , CA ,USA
    2, REGAL , MALLS , 100002 , NY , USA

    Hi,
    One way is to join t_transactions to 4 copies of t_key_values:
    SELECT  t.version_id
    ,       v.value           AS vendor
    ,       p.value           AS prefix
    ,       t.col_reciptid
    ,       s.value           AS state
    ,       c.value           AS country
    FROM    t_transactions  t
    JOIN    t_key_values    v  ON  v.key_id  = t.col_vendor
    JOIN    t_key_values    p  ON  p.key_id  = t.col_prefix
    JOIN    t_key_values    s  ON  s.key_id  = t.col_state     -- or col_sate
    JOIN    t_key_values    c  ON  c.key_id  = t.col_country
    If you'd care to post CREATE TABLE and INSERT statements for the sample data, then I could test this.
    The query above assumes all 4 coded columns in t_transactions have matching values in t_key_values, as they do in the sample data.  If that assumption is wrong, then use outer joins in some (or all) of the places where I used inner joins above.
    Another approach is to UNPIVOT t_transactions into 4 times as many rows, do a single join to t_key_values, and then PIVOT those results back to the original number of rows.

  • Evaluated order of Pivot and UnPivot in select statement

    My research which evaluated order of select statement is below.
    1 from
    2 where (Join condition)
    3 start with
    4 connect by
    5 where (filter of rows)
    6 group by
    7 having
    8 model
    9 select
    10 order byMy question is Where Pivot clause and UnPivot clause ?
    http://download.oracle.com/docs/cd/E16338_01/server.112/e10592/statements_10002.htm

    Provided that you can specify columns created by the PIVOT clause both in the select and in the Order By clause, I think the pivot must be executed before them:
    SQL> r
      1  select job, d10,d20,d30 from emp
      2  pivot (sum(sal) for deptno in (10 as D10, 20 as d20, 30 as d30))
      3* order by d20
    JOB              D10        D20        D30
    CLERK                       800
    CLERK                      1100
    MANAGER                    2975
    ANALYST                    3000
    ANALYST                    3000
    SALESMAN                              1600
    PRESIDENT       5000
    MANAGER         2450
    SALESMAN                              1500
    SALESMAN                              1250
    CLERK           1300
    MANAGER                               2850
    SALESMAN                              1250
    CLERK                                  950
    Selezionate 14 righe.
    Piano di esecuzione
    Plan hash value: 1739977809
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |      |    14 |   518 |     5  (40)| 00:00:01 |
    |   1 |  SORT ORDER BY       |      |    14 |   518 |     5  (40)| 00:00:01 |
    |   2 |   HASH GROUP BY PIVOT|      |    14 |   518 |     5  (40)| 00:00:01 |
    |   3 |    TABLE ACCESS FULL | EMP  |    14 |   518 |     3   (0)| 00:00:01 |
    -----------------------------------------------------------------------------Max

  • UNPIVOT with two set of records

    Hi Gurus,
    I am using Oracle 11g Release 11.2.0.1.0
    OS: windows
    Table Structure
    EMPL0YEE_ROLE
    employee_id number
    ROLE_1 VARCHAR2(10)
    ROLE_2 VARCHAR2(10)
    ROLE_3 VARCHAR2(10)
    ROLE_4 VARCHAR2(10)
    ROLE_5 VARCHAR2(10)
    MANAGER_1 VARCHAR2(10)
    MANAGER_2 VARCHAR2(10)
    MANAGER_3 VARCHAR2(10)
    MANAGER_4 VARCHAR2(10)
    MANAGER_5 VARCHAR2(10)
    DATA
    EMPLOYEE_ID MANAGER_1 MANAGER_2 MANAGER_3 MANAGER_4 MANAGER_5 ROLE_1 ROLE_2 ROLE_3 ROLE_4 ROLE_5
    1345 John Mike Ram Kumar DBA Sql Dev PLSQL Admin
    1 rows selected
    I want a output like this
    EMPLOYEE_ID MANAGER ROLE1
    1345 John DBA
    1345 Mike SQL DEV
    1345 Ram PLSQL
    1345 Kumar Admin
    I have tried with UNPIVOT
    I am able to get manager and role in two different queries
    SELECT
    EMPLOYEE_ID
    ,MANAGER
    FROM
    EMPLOYEE_ROLE
    UNPIVOT( MANAGER
    FOR col1
    in (MANAGER_1,
    MANAGER_2,
    MANAGER_3,
    MANAGER_4,
    MANAGER_5
    EMPLOYEE_ID            MANAGER   
    1345                   John      
    1345                   Mike      
    1345                   Ram       
    1345                   Kumar     
    4 rows selected
    SELECT
    EMPLOYEE_ID
    ,ROLE1
    FROM
    EMPLOYEE_ROLE
    UNPIVOT( ROLE1
    FOR col1
    in (ROLE_1,
    ROLE_2,
    ROLE_3,
    ROLE_4,
    ROLE_5
    EMPLOYEE_ID            ROLE1     
    1345                   DBA       
    1345                   Sql Dev   
    1345                   PLSQL     
    1345                   Admin  
    4 rows selected
    WHEN I tried adding 2 UNPIVOT clauses i got
    SELECT
    EMPLOYEE_ID
    ,ROLE1
    ,MANAGER
    FROM
    EMPLOYEE_ROLE
    UNPIVOT( ROLE1
    FOR col1
    in (ROLE_1,
    ROLE_2,
    ROLE_3,
    ROLE_4,
    ROLE_5
    UNPIVOT( MANAGER
    FOR col2
    in (MANAGER_1,
    MANAGER_2,
    MANAGER_3,
    MANAGER_4,
    MANAGER_5
    it is giving me cartesian product as given below
    EMPLOYEE_ID            ROLE1      MANAGER    
    1345                   DBA        John      
    1345                   DBA        Mike      
    1345                   DBA        Ram       
    1345                   DBA        Kumar     
    1345                   Sql Dev    John      
    1345                   Sql Dev    Mike      
    1345                   Sql Dev    Ram       
    1345                   Sql Dev    Kumar     
    1345                   PLSQL      John      
    1345                   PLSQL      Mike      
    1345                   PLSQL      Ram       
    1345                   PLSQL      Kumar     
    1345                   Admin      John      
    1345                   Admin      Mike      
    1345                   Admin      Ram       
    1345                   Admin      Kumar     
    16 rows selectedIs it possible to add two unpivots in a single UNPIVOT query.
    Any help is appreciated.
    Thanks!
    Regards,
    Gatha
    Edited by: Gatha on Sep 27, 2011 1:50 PM
    Edited by: Gatha on Sep 27, 2011 1:51 PM
    Edited by: Gatha on Sep 27, 2011 1:53 PM
    Edited by: Gatha on Sep 27, 2011 2:40 PM

    You can use an object so that the couple (MANAGER, ROLE) is considered as a single column to unpivot :
    SQL> create or replace type role_manager_obj as object (manager varchar2(10), role varchar2(10))
      2  /
    Type created
    SQL> WITH emp AS (
      2    SELECT employee_id
      3         , case when manager_1 is not null then role_manager_obj(manager_1, role_1) end as rm1
      4         , case when manager_2 is not null then role_manager_obj(manager_2, role_2) end as rm2
      5         , case when manager_3 is not null then role_manager_obj(manager_3, role_3) end as rm3
      6         , case when manager_4 is not null then role_manager_obj(manager_4, role_4) end as rm4
      7         , case when manager_5 is not null then role_manager_obj(manager_5, role_5) end as rm5
      8    FROM employee_role
      9  )
    10  SELECT employee_id
    11       , treat(rm_obj as role_manager_obj).manager as manager
    12       , treat(rm_obj as role_manager_obj).role as role
    13  FROM emp
    14  UNPIVOT(rm_obj FOR rm IN (rm1, rm2, rm3, rm4, rm5))
    15  ;
    EMPLOYEE_ID MANAGER    ROLE
           1345 John       DBA
           1345 Mike       SQL DEV
           1345 Ram        PLSQL
           1345 Kumar      Admin
    Or, doing it the old way, with a cross join :
    SQL> WITH five_rows AS ( SELECT level i FROM dual CONNECT BY level <= 5 )
      2  SELECT employee_id
      3       , manager
      4       , role
      5  FROM (
      6    SELECT e.employee_id
      7         , case t.i when 1 then manager_1
      8                    when 2 then manager_2
      9                    when 3 then manager_3
    10                    when 4 then manager_4
    11                    when 5 then manager_5
    12           end as manager
    13         , case t.i when 1 then role_1
    14                    when 2 then role_2
    15                    when 3 then role_3
    16                    when 4 then role_4
    17                    when 5 then role_5
    18           end as role
    19    FROM employee_role e
    20         CROSS JOIN five_rows t
    21  )
    22  WHERE manager IS NOT NULL
    23  ;
    EMPLOYEE_ID MANAGER                                  ROLE
           1345 John                                     DBA
           1345 Mike                                     SQL DEV
           1345 Ram                                      PLSQL
           1345 Kumar                                    Admin
    Edited by: odie_63 on 27 sept. 2011 13:04

  • ORA-56901: non-constant expression is not allowed for pivot|unpivot values

    Getting following errors
    ORA-56901: non-constant expression is not allowed for pivot|unpivot values
    ORA-06512: at "APPS.PIVOT_AWARD", line 16
    ORA-06512: at line 5
    when i run the following function it is giving error as above.
    can you please help me
    create or replace
    Function Pivot_award return sys_refcursor
    IS
       v_dept    VARCHAR2 (20000);
       v_query   VARCHAR2 (1000);
       op_rs sys_refcursor;
    BEGIN
      SELECT LISTAGG(award_number,',') WITHIN GROUP (ORDER BY award_id)
      INTO V_DEPT FROM xxdl.XXDL_CD_SCHEDULE_K_GTT ;
       v_query :=
          'SELECT *
            FROM (
            select award_name, award_id,award_number from xxdl.XXDL_CD_SCHEDULE_K_GTT)
            PIVOT(max(VAL) for award_number in  ('||v_dept||'))';
       OPEN op_rs FOR v_query;
       return op_rs;
    END;
    SELECT LISTAGG(award_number,',') WITHIN GROUP (ORDER BY award_id)
      INTO V_DEPT FROM xxdl.XXDL_CD_SCHEDULE_K_GTT ;
    Result of 1st query is PPE_T_CAPITAL,XIBNG,XIABP,XIABQ,XIABR,XIABS,XIABT,XIABU,XIABV,XIABW,XIAAE,XIAAF,XIAAG,XIAAH,XIAAI,XIAAJ,XIAAK,XIAAL,XIAAM,XIAAN,XIAAO,XIAAP,XIAAQ,XIAAR,XIAAS,XIAAU,XIAAU,XIAAV,XIAAZ,XIABD,XIABE,XIABF,XIABG,XIABH,XIABI,XIABJ,XIABK,XIABL,XIABM,XIABN,XIAAA,XIAAB,XIAAC,XIAAD,XIABY,XIABZ,XIACA,XIACB,XIACC,XIACD,XIACE,XIACF,XIACG,XIACH,XIACI,XIABA,XIAAW,XIAAX,XIAAY,XIACN,XIACT,XIACU,XIACP,AAAEX,XIACW,XIADC

    Hi Frank,
    Here is the create table and insert script. This is needed for me to show in report rows to columns.
    create table award_test(
      AWARD_NUMBER                            VARCHAR2 (15) ,                                                                                                                                                                                
    AWARD_NAME                              VARCHAR2(30)  ,                                                                                                                                                                               
    TOTAL_PROCEEDS                          NUMBER    ,                                                                                                                                                                                   
    EARNING_PROCS                           NUMBER    ,                                                                                                                                                                                   
    TOT_PROCS_EARNINGS                      NUMBER   ,                                                                                                                                                                                    
    GROSS_PROCS                             NUMBER   ,                                                                                                                                                                                    
    PROC_REF_DEF_ESCR                       NUMBER   ,                                                                                                                                                                                    
    OTH_UNSP_PROCS                          NUMBER  ,                                                                                                                                                                                     
    ISSUANCE_COST                           NUMBER   ,                                                                                                                                                                                    
    WORK_CAP_EXP                            NUMBER 
    --insert script
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAE','CEFA CP',300000000,200,300000200,300,500,600,0,700);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABG','CEFA K',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAS','Escondido Village #3',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('AAAEX','SU2009A',801806000,null,801806000,null,null,null,1806000,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABI','CEFA L-6',17815000,null,17815000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAP','CEFA R',115050508.15,null,115050508.15,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIACG','CEFA D',53150000,null,53150000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAB','Stu Union-1962',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAA','Notes Payable-Commercial Paper',350000000,null,350000000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABZ','CEFA L-3',9840000,null,9840000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAV','CEFA B',18106540,null,18106540,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAI','Medium Term Notes - Tranche 3',50000000,null,50000000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAZ','Recycling Pool',473379904.44,null,473379904.44,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAY','CEFA T2',187550000,null,187550000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAM','GMAC',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAU','CEFA A/K',16922982,null,16922982,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAC','SU TB 2002A - PARS',50000000,null,50000000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABL','CEFA L-9',15490000,null,15490000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABY','CEFA L-2',8775000,null,8775000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAJ','Frat 1&2',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAW','CEFA S',180727500,null,180727500,null,null,null,-472500,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAQ','Escondido Village #1',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIACW','CEFA U',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIACF','CEFA E',19753227.34,null,19753227.34,null,null,null,-106772.66,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIACN','CEFA T3',27562758.96,null,27562758.96,null,null,null,-47941.04,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAG','Medium Term Notes - Tranche 1',50000000,null,50000000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('PPE_T_CAPITAL','PPE_T_CAPITAL',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAK','Frat 3',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAF','Tresidder',0,null,0,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIABH','CEFA L',5055000,null,5055000,null,null,null,0,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAU','CEFA A/K',6605655,null,6605655,null,null,null,-74345,null);
    Insert into "award_test" (AWARD_NUMBER,AWARD_NAME,TOTAL_PROCEEDS,EARNING_PROCS,TOT_PROCS_EARNINGS,GROSS_PROCS,PROC_REF_DEF_ESCR,OTH_UNSP_PROCS,ISSUANCE_COST,WORK_CAP_EXP) values ('XIAAD','SU 2024 Bonds',150000000,null,150000000,null,null,null,0,null);Expected output rows to columns (i took first two insert statements)
    'XIAAE','CEFA CP',300000000,200,300000200,300,500,600,0,700
    'XIABG','CEFA K',0,null,0,null,null,null,0,null
    I need to have awardnumber and corresponding details below
    'XIAAE'       'XIABG'
    'CEFA CP'    'CEFA K'
    300000000   0
    200             null
    300000200   0
    This way i need to get all the information vertically with awardnumber. I have written following code but it is not working.
    create or replace
    Function Pivot_award return sys_refcursor
    IS
       v_dept    VARCHAR2 (20000);
       v_query   VARCHAR2 (1000);
       op_rs sys_refcursor;
    BEGIN
      SELECT LISTAGG('''' || award_number || '''',',') WITHIN GROUP (ORDER BY award_number)
      INTO V_DEPT FROM award_test ;
       v_query :=
          'SELECT *  from award_test
            UNPIVOT(VAL for operator in(                                                                                                                                                                                                       
    AWARD_NAME,                                                                                                                                                                                                              
    TOTAL_PROCEEDS,                                                                                                                                                                                                             
    EARNING_PROCS ,                                                                                                                                                                                                              
    TOT_PROCS_EARNINGS ,                                                                                                                                                                                                           
    GROSS_PROCS    ,                                                                                                                                                                                                               
    PROC_REF_DEF_ESCR ,                                                                                                                                                                                                        
    OTH_UNSP_PROCS ,                                                                                                                                                                                                              
    ISSUANCE_COST ,                                                                                                                                                                                                            
    WORK_CAP_EXP ))
            PIVOT(max(VAL) for award_number in  ('||v_dept||'))';
       OPEN op_rs FOR v_query;
       return op_rs;
    END;throwing an error ORA-06502: PL/SQL: numeric or value error: character string buffer too small
    ORA-06512: at "APPS.PIVOT_AWARD", line 11
    ORA-06512: at line 5
    also when i run simple query
    SELECT *  from award_test
            UNPIVOT(VAL for operator in(                                                                                                                                                                                                       
    AWARD_NAME,                                                                                                                                                                                                              
    TOTAL_PROCEEDS,                                                                                                                                                                                                             
    EARNING_PROCS ,                                                                                                                                                                                                              
    TOT_PROCS_EARNINGS ,                                                                                                                                                                                                           
    GROSS_PROCS    ,                                                                                                                                                                                                               
    PROC_REF_DEF_ESCR ,                                                                                                                                                                                                        
    OTH_UNSP_PROCS ,                                                                                                                                                                                                              
    ISSUANCE_COST ,                                                                                                                                                                                                            
    WORK_CAP_EXP ))
            PIVOT(max(VAL) for award_number in  ('PPE_T_CAPITAL','XIBNG','XIABP')) Throwing an error
    ora-01790 Expression must have same datatype as correspoding expression
    Edited by: 893185 on Nov 10, 2011 2:00 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • UNPIVOT

    Can anyone please tell me what's wrong with the following query? I'm using TOAD
    SELECT *
      FROM   bin_data
       UNPIVOT (
                    direction                          
                FOR bin_data                           
                IN  (bin_1_data, bin_2_data, bin_3_data)
               );I'm getting the following error:
    ORA-00933: SQL command not properly ended
    Thanks
    PS: Its oracle 10g database
    Edited by: thinkingeye on Aug 27, 2010 10:43 AM

    Hi,
    You can unpivot in any version of Oracle by cross-joining with a table (in practice, usually a result set) that has as many rows as there are columns to unpivot.
    For example:
    WITH     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    SELECT     CASE     c.n
              WHEN  1       THEN  b.bin_1_data
              WHEN  2       THEN  b.bin_2_data
              WHEN  3       THEN  b.bin_3_data
         END     AS bin_data
    ,     ...     -- whatever other columns you need
    FROM          bin_data    b
    CROSS JOIN     cntr         c
    ;Remember to convert the unpivoted columns to the same data type, if they aren't already the same type.

  • Need Help with Creating the SQl query

    Hi,
    SQL query gurus...
    INFORMATION:
    I have two table, CURRENT and PREVIOUS.(Table Defs below).
    CURRENT:
    Column1 - CURR_PARENT
    Column2 - CURR_CHILD
    Column3 - CURR_CHILD_ATTRIBUTE 1
    Column4 - CURR_CHILD_ATTRIBUTE 2
    Column5 - CURR_CHILD_ATTRIBUTE 3
    PREVIOUS:
    Column1 - PREV_PARENT
    Column2 - PREV_CHILD
    Column3 - PREV_CHILD_ATTRIBUTE 1
    Column4 - PREV_CHILD_ATTRIBUTE 2
    Column5 - PREV_CHILD_ATTRIBUTE 3
    PROBLEM STATEMENT
    Here the columns 3 to 5 are the attributes of the Child. Lets assume that I have two loads, One Today which goes to the CURRENT table and one yesterday which goes to the PREVIOUS table. Between these two loads there is a CHANGE in the value for Columns either 3/4/5 or all of them(doesnt matter if one or all).
    I want to determine what properties for the child have changed with the help of a MOST efficient SQL query.(PARENT+CHILD is unique key). The Database is ofcourse ORACLE.
    Please help.
    Regards,
    Parag

    Hi,
    The last message was not posted by the same user_name that started the thread.
    Please don't do that: it's confusing.
    Earlier replies give you the information you want, with one row of output (maximum) per row in current_tbl. There may be 1, 2 or 3 changes on a row.
    You just have to unpivot that data to get one row for every change, like this:
    WITH     single_row  AS
         SELECT     c.curr_parent
         ,     c.curr_child
         ,     c.curr_child_attribute1
         ,     c.curr_child_attribute2
         ,     c.curr_child_attribute3
         ,     DECODE (c.curr_child_attribute1, p.prev_child_attribute1, 0, 1) AS diff1
         ,     DECODE (c.curr_child_attribute2, p.prev_child_attribute2, 0, 2) AS diff2
         ,     DECODE (c.curr_child_attribute3, p.prev_child_attribute3, 0, 3) AS diff3
         FROM     current_tbl    c
         JOIN     previous_tbl   p     ON  c.curr_parent     = p.prev_parent
                                AND c.curr_child     = p.prev_child
         WHERE     c.curr_child_attribute1     != p.prev_child_attribute1
         OR     c.curr_child_attribute2     != p.prev_child_attribute2
         OR     c.curr_child_attribute3     != p.prev_child_attribute3
    ,     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    SELECT     s.curr_parent     AS parent
    ,     s.curr_child     AS child
    ,     CASE     c.n
              WHEN  1  THEN  s.curr_child_attribute1
              WHEN  2  THEN  s.curr_child_attribute2
              WHEN  3  THEN  s.curr_child_attribute3
         END          AS attribute
    ,     c.n          AS attribute_value
    FROM     single_row     s
    JOIN     cntr          c     ON     c.n IN ( s.diff1
                                    , s.diff2
                                    , s.diff3
    ORDER BY  attribute_value
    ,            parent
    ,            child
    ;

Maybe you are looking for

  • Pros/cons of using iPod as backup HD?

    Ok, I'm the last person on the planet without an iPod, but thinking of getting one. I'm wondering if I can get away with using an iPod for both music and as my backup HD (instead of using an external FW HD) for my primary HD (this would get me halfwa

  • DNS: looking up IP address returns Comcast name, bad?

    I am planning out the setup of a mail server and I have this nibbling bad feeling about DNS and IP address and hostname and that other mail servers might not want to receive mail from us if our hostname and the ip address and the hostname returned in

  • Help with number

    I want to check for numbers in a "IF statement". Say if I got 0-10000 as a value, I want to only check for value between 1000-10000.

  • How do I branch based on validation success or failure?

    I am on an edit record page. I want to be able to branch based on clicking on the submit button and whether all of my validations pass (branch to different page) or a single validation fails (return to edit page with error message). I know how to set

  • Group Membership Cache TTL

    Hi, I'm using WebLogic 6.10 sp1 with an extended AbstractListableRealm (using a LDAP-Server). I'm also using a CachingRealm with GroupCaching = enabled. Actual I have about 95 Users and 4 Groups. My Problem: if I set "Group Membership Cache TTL" to 3