PIVOT and UNPIVOT

I have a column called Qty and AMt
QTY     AMT
1          2
1           1
2           2
I need to pivot/unpivot this in such a way that I need a collumn called Measurecode and Measure
MeasureCode         Measure
QTY                            1
AMT                             2
QTY                             1
AMT                              1
QTY                              2
AMT                              2
How do I do this?
SPPandey

You must have a column that uniquely identifies each row in the original table. Otherwise, after unpivot shuffle rows may occur. For example, if you need sorting by Measure column.
-- code #1
;with QA as (
SELECT ID, 1 as Seq, QTY, AMT
from table
union all
SELECT ID, 2, QTY, AMT
from table
SELECT ID,
MeasureCode= case when Seq=1 then 'QTY' else 'AMT' end,
Measure= case when Seq=1 then QTY else AMT end
from QA
order by ID, MeasureCode desc;
or
-- code #2
SELECT ID, MeasureCode, Measure
from table
unpivot (Measure for MeasureCode in (QTY, AMT)) as U;
If there is no column that identifies the rows, you can create temporary column with sequence before the unpivot:
-- code #2 v2
SELECT Seq, MeasureCode, Measure
from (SELECT Seq= row_number() over (order by (SELECT 0)), QTY, AMT from table) as S
unpivot (Measure for MeasureCode in (QTY, AMT)) as U;
José Diz     Belo Horizonte, MG - Brasil

Similar Messages

  • 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

  • Are Pivot and Unpivot supported in SSRS

    We're upgrading from SSRS 2005 to 2008 R2.  I'm rewriting some of my reports and using Unpivot. In SQL it works fine when I run it against the database.  But in SSRS (BIDS 2008) when I paste the working SQL statement into the Query Builder, I get
    an error that "The UNPIVOT SQL construct or statement is not supported".  If i click OK and preview my report, it does run.  So, I'm not sure why I'm getting this error.  Has anyone had experience with this?
    Milissa Hartwell

    Thats a known issue with query designer in SSRS. You dont need to worry much on it as report still works fine. If you're so concerned on the pop up make query into a stored procedure and call stored procedure from SSRS dataset query. Then you wont get
    any of these issue.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Pivot and Unpivot in Oracle 10g

    Hi,
    This is my table structure
    CREATE TABLE TESTTABLE
    REVENUE1 NUMBER,
    REVENUE2 NUMBER,
    REVENUE3 NUMBER,
    YEAR DATE
    insert into testtable(revenue1, revenue2, revenue3, year) values(100,200,300,'1-Jan-2009') ;
    insert into testtable(revenue1, revenue2, revenue3, year) values(250,350,450,'1-Jan-2010') ;
    insert into testtable(revenue1, revenue2, revenue3, year) values(300,400,500,'1-Jan-2011') ;
    The resultant should be on oracle 10g.
    The result should be like
    1-Jan-2009 1-Jan-2010 1-Jan-2011
    Revenue1 100 250 300
    Revenue2 200 350 400
    Revenue3 300 450 500
    Thanks in advance

    Hi,
    Naveen wrote:
    ...Thanks for the reply but this will not make the year as the column header it will be shown as a row in the result set.That's exactly what I thought you wanted, based on your first message:
    Naveen wrote:
    The result should be like
    1-Jan-2009 1-Jan-2010 1-Jan-2011
    Revenue1 100 250 300
    Revenue2 200 350 400
    Revenue3 300 450 500It would have been clearer if you had said: "The result set should be like these 3 rows:
    {code}
    Label 1-Jan-2009 1-Jan-2010 1-Jan-2011
    Revenue1 100 250 300
    Revenue2 200 350 400
    Revenue3 300 450 500
    {code}
    When posting formatted text (such as results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    Column names are hard-coded into the query.  To get variable data, such as '1-Jan-2009' as a column header, you must use dynamic SQL.  This is probably best done in your front-end.  SQL*Plus, for example, has substitution variables, that you can define with data from your table at run-time using the COLUMN ... NEW_VALUE command.  (SQL*Plus also has a COLUMN ... HEADING command that can do what you want, , but it doesn't simplify this particular problem.)
    What front-end tool are you using?  Can you use SQL*Plus?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Pivot and dynamic SQL

    Hi Team,
    I need to write a SQL to cater the requirements. Below is my requirements:
    pagename fieldname fieldvalue account_number consumerID
    AFAccountUpdate ArrangementsBroken dfsdff 1234 1234
    AFAccountUpdate ArrangementsBroken1 dfsdff 1234 1234
    AFAccountUpdate ArrangementsBroken2 dfsdff 1234 1234
    AFAccountUpdate ArrangementsBroken2 dfsdff 12345 12345
    AFAccountUpdate ArrangementsBroken1 addf 12345 12345
    Create table test_pivot_dynamic
    pagename varchar(200),
    fieldname Varchar(200),
    fieldvalue varchar(500),
    N9_Router_Account_Number bigint,
    TC_Debt_Item_Reference bigint
    --Input
    insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken','addf',1234,1234)
    insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfsdff',1234,1234)
    insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','fder',1234,1234)
    insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken2','dfdfs',12345,12345)
    insert into test_pivot_dynamic Values('AFAccountUpdate','ArrangementsBroken1','dfdwe',12345,12345)
    insert into test_pivot_dynamic Values('AFAccountUpdate1','Arrangements','addf',1234,1234)
    insert into test_pivot_dynamic Values('AFAccountUpdate1','Test1','dfsdff',1234,1234)
    --Expected output:
    Select 1234,1234,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfsdff','ArrangementsBroken2','fder','ArrangementsBroken2','fder'
    Select 12345,12345,'AFAccountUpdate','ArrangementsBroken','addf','ArrangementsBroken1','dfdwe','ArrangementsBroken2','dfdfs'
    Select 1234,1234,'AFAccountUpdate1','Arrangements','addf','Test1','dfsdff'
    so basically we have to pivot and dynamic sql and insert the expected output to a common table which will have all the required fields
    Thanks,Ram.
    Please don't forget to Marked as Answer if my post solved your problem and use Vote As Helpful if a post was useful. It will helpful to other users.

    This should give you what you're looking for
    SELECT N9_Router_Account_Number,TC_Debt_Item_Reference,PageName,
    MAX(CASE WHEN SEQ = 1 THEN fieldname END) AS fieldname1,
    MAX(CASE WHEN SEQ = 1 THEN fieldvalue END) AS fieldvalue1,
    MAX(CASE WHEN SEQ = 2 THEN fieldname END) AS fieldname2,
    MAX(CASE WHEN SEQ = 2 THEN fieldvalue END) AS fieldvalue2,
    MAX(CASE WHEN SEQ = 3 THEN fieldname END) AS fieldname3,
    MAX(CASE WHEN SEQ = 3 THEN fieldvalue END) AS fieldvalue3,
    MAX(CASE WHEN SEQ = 4 THEN fieldname END) AS fieldname4,
    MAX(CASE WHEN SEQ = 4 THEN fieldvalue END) AS fieldvalue4
    FROM
    SELECT *,ROW_NUMBER() OVER (PARTITION BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName ORDER BY PageName) AS SEQ,*
    FROM test_pivot_dynamic
    )t
    GROUP BY N9_Router_Account_Number,TC_Debt_Item_Reference,PageName
    To make it dynamic see
     http://www.beyondrelational.com/modules/2/blogs/70/posts/10791/dynamic-crosstab-with-multiple-pivot-columns.aspx
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Pivot and chart drill down

    Hi ,
    Could anyone please let me know how to drill down in pivot and related chart report .
    As because when I drill i get a table view instead of chart.
    Regards,
    Megha

    Hi,
    I believe you are trying to show chart of your pivot table as well in your pivot view. I tried and I can drill down from both chart and its pivot table.
    You need to select drill option under Interaction tab of Additional Charting Option properties of this chart. Save your report and see if drill down in pivot table and in chart in the Pivot view is working.
    Regards,
    Rituraj Kumar.

  • Pivoting and string manipulation

    Hi Guys I would appreciate your help with this.
    I have a table with a single column= A1, A2, B1, C1, C2 which I need to pivot and write the following rows to a second table again as a single column;
    A1,B1,C1
    A1,B1,C2
    A2,B1,C1
    A2,B1,C2
    An example would be great. Thanks in advance.
    Gaz

    Hi,
    Gaz wrote:
    ... Hope this covers all your questionsNo.
    Frank Kulash wrote:
    ... Explain the business rules as clearly as you can. Why don't you want rows like the following in the second table:
    C1, B1, A1
    B1, B1, B1
    A1, A2, B1or do you?
    Do you know, in advance, that the strings all start with 'A', 'B' or 'C', or does the query have to figure out what the different possibilites are?I made several guesses.
    INSERT INTO     target_tab (col1)
    WITH  normalized_source_tab     AS
         SELECT     REGEXP_SUBSTR ( col1
                                , '[^ ,]+'
                         , 1
                         , LEVEL
                         )          AS txt
         ,     DENSE_RANK () OVER ( ORDER BY  REGEXP_SUBSTR ( col1
                                                                     , '[^ ,0-9]+'
                                                  , 1
                                                  , LEVEL
                                 )          AS prefix_num
         FROM     source_tab
         CONNECT BY     LEVEL <= 1 + LENGTH (col1)
                                 - LENGTH (REPLACE (col1, ','))
    SELECT     SUBSTR ( SYS_CONNECT_BY_PATH (txt, ', ')
                , 3
    FROM     normalized_source_tab
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     prefix_num     = 1
    CONNECT BY     prefix_num     = 1 + PRIOR prefix_num     
    ;Among other things, I guessed that the comma-delimited items in sorce_tab.col1 always follow this pattern:
    (1) Optional spaces, to be ignored
    (2) Non-digits, which deterrmine the postion in target_tab.col1
    (3) Digits
    Either (2) or (3), but not both, may be omitted. If both are present, (3) may come before (2).

  • Does SharePoint 2013 have Power Query services similar to Power Pivot and Power View?

    Does SharePoint 2013 include services to host/support Power Query content similar to the way it hosts Power Pivot content in the Power Pivot Gallery? 

    Miguel.  Is there an update to this?  New information or new timeline?
    We have SP 2013 Enterprise, on-prem.  I'm finding that Power Query 's ability to get CSV or XML or other Web Services content, and then load it up to PowerPivot, is a way to address the lack of ODATA connectivity options on the web.  :-(
    I would very much like to be able to create an XLS doc, with a Power Query to a CSV file, Loaded to PowerPivot, and have SP's Excel Services/PowerPivot engine continue to update the content for me.  It fails today, as you stated above.
    Do you even think this will be updated for the on-prem version of SharePoint 2013 or will it only live in Power BI for Office 365?

  • Excel framework and pivots and charts

    Can you point to an excle spreadsheet with pivot tables and charts/dashboards? I have not used the excel portlet suite since PT 4.5.

    Don't worry, Mickey, it hasn't changed a lick since then. :-)
    You always could point to a range in a pivot table and to a chart. Ranges, including those created by a pivot table, will be displayed as static HTML tables w/o formatting and charts will be exported to JPGs and displayed pretty much exactly as they look in the workbook.
    Chris Bucchere | bdg | [email protected] | http://www.thebdgway.com

  • Default Max rows for pivot and table view that can display

    Hi Experts,
    what was the Maximum number of pivot table records,Maximum number of pivot table populated cells,Maximum number of table view rows by default in OBIEE.
    If i want to see where i can found all these things in OBIEE.
    If i want to change the default range of these rows is there any maximum limit for setting manually also or we can set any number of records.(i.e. if i want to display 100000 records will accept or there will be any range for setting also)
    Thanks,
    Edited by: RAJ.bi on Aug 5, 2012 8:12 AM

    Check the below link for the same
    http://docs.oracle.com/cd/E25178_01/bi.1111/e10541/answersconfigset.htm
    If you are going with 100K records per view, I think there is a limit for downloading into spread sheet.
    Pls mark correct or helpful

  • 11g PIVOT and NULL

    Hi,
    My question is reagrding the PIVOT clause introduced in 11g.
    How do I specify a value for NULL?
    Let me explain that more with an example:
    Code:
    WITH t1 as
    SELECT 1 AS emp_id, 10 AS sales FROM DUAL UNION ALL
    SELECT 1 AS emp_id, 20 AS sales FROM DUAL UNION ALL
    SELECT 2 AS emp_id, 10 AS sales FROM DUAL UNION ALL
    SELECT 3 AS emp_id, NULL AS sales FROM DUAL
    SELECT *
    FROM t1
    PIVOT ( MAX(sales) AS MAX_SALES
            FOR emp_id in (1, 2, 3)
          )Result:
    1_MAX_SALES 2_MAX_SALES 3_MAX_SALES
             20          10            The result I would like to see is:
    1_MAX_SALES 2_MAX_SALES 3_MAX_SALES
             20          10           0Any suggestions would be great.

    Here is a better example:
    WITH t1 as
        SELECT 10 as group_id,  1 AS emp_id, 10 AS sales FROM DUAL UNION ALL
        SELECT 10 as group_id,  1 AS emp_id, 20 AS sales FROM DUAL UNION ALL
        SELECT 10 as group_id,  2 AS emp_id, 10 AS sales FROM DUAL UNION ALL
        SELECT 20 as group_id,  3 AS emp_id, NULL AS sales FROM DUAL
    SELECT   *
        FROM t1
        PIVOT ( MAX(nvl(sales,0)) AS MAX_SALES
                FOR emp_id in (1, 2, 3)
    ORDER BY GROUP_IDThe result is:
      GROUP_ID 1_MAX_SALES 2_MAX_SALES 3_MAX_SALES
            10          20          10           
            20                                   0The result I am looking for:
      GROUP_ID 1_MAX_SALES 2_MAX_SALES 3_MAX_SALES
            10          20          10           0
            20           0           0           0

  • Need Help in Pivot of the Columns in Oracle 9i

    Hi,
    I have a requirement where-in i need to generate the output as below:<<under EXP1 we need to populate the SUM amounts for each category i.e. group by No and Category>>
    No Vessel EXP1 EXP2 EXP3 EXP3 .....
    1 TEST 10 -8 100 0
    2 TEST 11 0 90 -17
    And the Code I am using for the same as below:
    SELECT Vessel_Code,
               dano,          
               join(cursor(select 'SUM(DECODE(ExpenseCategory,'||''''||expensecategory||''''||',GroupAmount,NULL))'||' '||expensecategory
                           from linetypes
                           where ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
                           and ExpenseCategory NOT LIKE 'REBILLABLE%'
                           and ExpenseCategory NOT LIKE 'SPECIFIED%'
                           group by expensecategory))
        FROM
        (select     a.Vessel_Code        
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           b.ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory NOT LIKE 'REBILLABLE%'
        and         b.ExpenseCategory NOT LIKE 'SPECIFIED%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           b.ExpenseCategory
        Union
        select      a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1) as ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory LIKE 'SPECIFIED%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1)
        Union
        select      a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1) as ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory LIKE 'REBILLABLE%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1)
        GROUP BY Vessel_Code,
        dano
        order by dano;The reason why I have been using the join(cursor(.....) to get the result set as :
    SUM(DECODE(ExpenseCategory,'OWNER',GroupAmount,NULL)) OWNER,
               SUM(DECODE(ExpenseCategory,'CTM',GroupAmount,NULL)) CTM,
               SUM(DECODE(ExpenseCategory,'PORT',GroupAmount,NULL)) PORT,
               SUM(DECODE(ExpenseCategory,'REBILLABLE',GroupAmount,NULL)) REBILLABLE,
               SUM(DECODE(ExpenseCategory,'SPECIFIED',GroupAmount,NULL)) SPECIFIED,
               SUM(DECODE(ExpenseCategory,'CARGO',GroupAmount,NULL)) CARGO,
               SUM(DECODE(ExpenseCategory,'ACCTTEMP',GroupAmount,NULL)) ACCTTEMPAs we don't know the exact number of expense categories to be displayed I have used cursor excluding the expense categories I don't need.When I run the same as individual query I get the correct result but when I execute it along with the query I get error maximum cursors open exceeded...
    Please let me know how can it be achieved.
    Any suggestions are welcome.
    Thanks,
    Hemanth

    The easiest way to do this, and it could be done in a few minutes, would be to move to a currently supported version of Oracle, 11gR1 or 11gR2, where we have the PIVOT and UNPIVOT operators.
    In the desupported version you have the best choice is to hit http://asktom.oracle.com and look up the solution he published there some years ago.
    I don't have the link so you can find it as fast as I can but look under "pivot" and "crosstab."

  • How to display the rows in to columns and columns into rows?

    DES:- I know by using pivot and unpivot you can convert rows into columns and columns into rows but i don't know how to write the syntax?

    Hi,
    Besides the places Martin mentioned above, there are many examples in the forum FAQ:
    https://community.oracle.com/message/9362005#9362005
    For an example of both PIVOT and UNPIVOT in the same query, see
    http://forums.oracle.com/forums/thread.jspa?threadID=920854&tstart=0

  • Select with transposition and join

    Hi Guys!
    I'm using Oracle 9i and I'm facing the following problem:
    My table looks like this:
    Stripe
    Unit
    Value
    1
    1
    a1
    1
    2
    a2
    1
    3
    a3
    2
    1
    b1
    2
    2
    b2
    2
    3
    b3
    2
    4
    b4
    4
    1
    c1
    4
    2
    c2
    4
    3
    c3
    4
    4
    c4
    4
    5
    c5
    My result should look like this:
    Unit
    Stripe1 Value
    Stripe2 Value
    Stripe3 Value
    Stripe4 Value
    1
    a1
    b1
    c1
    2
    a2
    b2
    c2
    3
    a3
    b3
    c3
    4
    b4
    c4
    5
    c5
    I tried it with one select for each stripe and full joins, but in this example I would only see the first 3 units....
    Any ideas?

    Another way, but only if your on database version 11gR1 and onwards, is to use the PIVOT operator:
    SQL> -- generating sample date:
    SQL> with t as (
      2  select 1 stripe, 1 unit, 'a1' value from dual union
      3  select 1, 2, 'a2' from dual union
      4  select 1, 3, 'a3' from dual union
      5  select 2, 1, 'b1' from dual union
      6  select 2, 2, 'b2' from dual union
      7  select 2, 3, 'b3' from dual union
      8  select 2, 4, 'b4' from dual union
      9  select 4, 1, 'c1' from dual union
    10  select 4, 2, 'c2' from dual union
    11  select 4, 3, 'c3' from dual union
    12  select 4, 4, 'c4' from dual union
    13  select 4, 5, 'c5' from dual
    14  )
    15  --
    16  -- actual query:
    17  --
    18  select *
    19  from ( select unit
    20         ,      stripe
    21         ,      value
    22         from   t
    23       )
    24  pivot (max(value) for (stripe) in ( 1 as stripe1value
    25                                    , 2 as stripe2value
    26                                    , 3 as stripe3value
    27                                    , 4 as stripe4value
    28                                    )
    29        )
    30  order by unit;
          UNIT ST ST ST ST
             1 a1 b1    c1
             2 a2 b2    c2
             3 a3 b3    c3
             4    b4    c4
             5          c5
    5 rows selected.
    ORACLE-BASE - PIVOT and UNPIVOT Operators in Oracle Database 11g Release 1

  • Reg: PIVOTing XML -

    Hi Experts,
    I'm going through this nice article on PIVOT but the PIVOT XML doesn't seem to work as demonstrated.
    ORACLE-BASE - PIVOT and UNPIVOT Operators in Oracle Database 11g Release 1
    ranit@XE11GR2>> ed
    Wrote file c:\rb\1.sql
      1  select * from (
      2     select product_code --customer_id, quantity,
      3     from pivot_test
      4  ) PIVOT (
      5     COUNT(product_code) as prod
      6             FOR(product_code) in ('A','B','C')
      7* )
    ranit@XE11GR2>> /
      'A'_PROD   'B'_PROD   'C'_PROD
             4          2          3
    Elapsed: 00:00:00.01
    ranit@XE11GR2>> ed
    Wrote file c:\rb\1.sql
      1  select * from (
      2     select product_code --customer_id, quantity,
      3     from pivot_test
      4  ) PIVOT XML (
      5     COUNT(product_code) as prod
      6             FOR(product_code) in ('A','B','C')
      7* )
    ranit@XE11GR2>> /
                    FOR(product_code) in ('A','B','C')
    ERROR at line 6:
    ORA-00905: missing keyword
    Does it mean: hard-coded values can't at all be used inside the IN clause (and always it should be a sub-query) ?
    Any pointers? Help is much appreciated.
    Oracle version: Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production
    Thanks,
    Ranit

    Hi, Ranit.
    Review the documentation for PIVOT XML in the SQL Language manual:
    SELECT
    which says "You cannot specify XML when you specify explicit pivot values using expressions in the pivot_in_clause."
    Notice that none of the XML examples on the Oracle-Base page are like the one you posted.  I find Oracle-Base a little misleading when it says "Adding the XML keyword to the PIVOT operator allows us to convert the generated pivot results to XML format. It also makes the PIVOT a little more flexible, allowing us to replace the hard coded IN clause with a subquery, or the ANY wildcard."
    The XML keyword is actually requiring us to replace the hard coded IN clause.

Maybe you are looking for