Pivoting using sys_connect_by_path

Can you please let me know how to get this output using sys_connect_by_path hierarchical function ?
JOB DEPT_10 DEPT_20 DEPT_30 DEPT_40
CLERK 1 2 1 (null)
SALESMAN (null) (null) 4 (null)
PRESIDENT 1 (null) (null) (null)
MANAGER 1 1 1 (null)
ANALYST (null) 2 (null) (null)
I know how to acheive this by decode function.Even I have the query ready .
select job,
max( decode( deptno, 10, cnt, null ) ) dept_10,
max( decode( deptno, 20, cnt, null ) ) dept_20,
max( decode( deptno, 30, cnt, null ) ) dept_30,
max( decode( deptno, 40, cnt, null ) ) dept_40
from ( select job, deptno, count(*) cnt from emp group by job, deptno )
group by job
But my requirement is to get the same output by using SYS_CONNECT_BY_PATH.
Please let me know the query if its possible.Else let me know the reason why we cant do .

Hi,
Welcome to thre forum!
If you're using Oracle 11, then SELECT ... PIVOT can help do what you want. In any version, you can do something like what you're already doing, though you don't need a sub-query:
SELECT       job
,       SUM (DECODE (deptno, 10, 1))     AS dept_10
,       SUM (DECODE (deptno, 20, 1))     AS dept_20
,       SUM (DECODE (deptno, 30, 1))     AS dept_30
,       SUM (DECODE (deptno, 40, 1))     AS dept_40
FROM       scott.emp
GROUP BY  job
ORDER BY  job     -- If wanted
;Either way, SYS_CONNECT_BY_PATH doesn't help any.
The one reason why you might want to use SYS_CONNECT_BY_PATH is if you didn't know how many different departments there might be. In that case, you could do something like this:
WITH     got_cnt          AS
     SELECT       e.job
     ,       d.deptno
     ,       NULLIF (COUNT (e.deptno), 0)               AS cnt
     ,       DENSE_RANK () OVER (ORDER BY d.deptno)     AS d_num
     FROM             scott.dept  d
     LEFT OUTER JOIN  scott.emp   e   PARTITION BY (e.job)
                                        ON  d.deptno = e.deptno
     GROUP BY  e.job
     ,            d.deptno
SELECT       job
,       REPLACE ( SYS_CONNECT_BY_PATH ( NVL2 ( cnt
                                      , TO_CHAR (cnt, '9999')
            )          AS all_cnts
FROM       got_cnt
WHERE       CONNECT_BY_ISLEAF     = 1
START WITH     d_num     = 1
CONNECT BY     d_num     = PRIOR d_num + 1
     AND     job     = PRIOR job
ORDER BY  job
;As you can see, it's quite a bit more complicated than what you already have, and it's less efficient.
Also, it doesn't produce separate columns for each depararment. All the departments are concatenated together, formatted so they look like separate columns. Also, the query above doesn't have a header identifiyuing which department corresponds to each "column" , but you could fix that by doing a UNION with another CONNECT BY query to generate a header row.
To get truly separate columns, you could use various string manipulation techniques to split the results of SYS_CONNECT_BY_PATH into separate columns, but that requires knowing exactly how many departments to expect, which defeats the purpose of using SYS_CONNECT_BY_PATH.

Similar Messages

  • 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.

  • How to get text from column  labels in pivot using javascript?

    Hi, is it possible to get text from column labels in pivot using javascript? How?

    You don't get a response from a URLRequest, you get the response from a URLLoader:
    View this sample page for URLRequest and URLLoader and I think it'll make more sense to you.
    http://help.adobe.com/en_US/air/reference/html/flash/net/URLRequest.html#URLRequest()

  • How to pivot using pivot clause of sqlserver 2005 for three values

    Dear all
                Is it possible to formulate the query using pivote clause of sqlserver 2005.
    ( Table name is) BridgeHawra
    ReportDate,                 , Pole, DiameterCost,Flag,OuterDiaCost
    01 jan 2014,               ,1     ,   4.5      ,yes,6
    01 jan 2014,               ,2     ,   4.5        ,no,6
    01 jan 2014,               ,3    ,  5.5         ,no,6
    02 jan 2014,               ,4     ,  5.5        ,no,5.9
    02 jan 2014,               ,5     ,  5.5        ,no,6
    1)Pole Col will have unique value.
    o2)One pole will have one DiameterCost, but n number of DiameterCost can be there.
    I have to show a report which should show , count of poles and cost(DiameterCost* pole count of the day of each DiameterCost) for each date and DiameterCost.
    as following
    DateOfReport            ,  PoleCountofDiameterCost4.5, DiameterCost4.5, PoleCountOfDiameterCost5.5,DiameterCost5.5
    01 jan 2014              , 2                                      
          ,(2*4.5)                        ,1                                   
    ,(1*5.5)
    02 jan 2014              , 0/null                                      ,0/null
                              ,2                                
       ,(2*5.5)
    yours sincerely

    Yes it is possible though you need to use dynamic pivot technique. Dynamic pivot allow you to select/display column names dynamically.
    Below example does not use dynamic pivot,
    --create table #temp(ReportDate datetime,Pole int, DiameterCost decimal(5,2),Flag varchar(3),OuterDiaCost decimal(5,2))
    --insert into #temp values('01 jan 2014',1,4.5,'yes',6)
    --insert into #temp values('01 jan 2014',2,4.5,'no',6)
    --insert into #temp values('01 jan 2014',3,5.5,'no',6)
    --insert into #temp values('02 jan 2014',4,5.5,'no',5.9)
    --insert into #temp values('02 jan 2014',5,5.5,'no',6)
    ;with cte as (
    select ReportDate,
    DiameterCost * PoleCount as DiameterCost,
    PoleCount ,
    'PoleCountofDiameterCost'+cast(DiameterCost as varchar) column1,
    'DiameterCost'+cast(DiameterCost as varchar) column2
    from (
    select ReportDate,DiameterCost,Count(Pole) as PoleCount from #temp
    group by ReportDate,DiameterCost
    ) x
    ),cte1 as (
    select * from cte
    pivot( max(PoleCount) for column1 in ([PoleCountofDiameterCost4.50],[PoleCountofDiameterCost5.50])
    ) pvt
    pivot( max(DiameterCost) for column2 in ([DiameterCost4.50],[DiameterCost5.50])
    ) pvt1
    select ReportDate,
    Max([PoleCountofDiameterCost4.50]) [PoleCountofDiameterCost4.50],
    Max([DiameterCost4.50]) [DiameterCost4.50],
    Max([PoleCountofDiameterCost5.50]) [PoleCountofDiameterCost5.50],
    Max([DiameterCost5.50]) [DiameterCost5.50] from cte1
    group by ReportDate
    Regards, RSingh

  • Pivoting using Model Clause Vs pivoting using Aggregate Fun(Case) statement

    Hi,
    I just wanted to know which option is better for pivoting the data if the data is like:
    Grp1 Grp2 Day_week Sales
    1 1 Sun 200
    1 1 Mon 100
    1 2 Sun 1000
    and so on...
    The output should be:
    Grp1 Grp2 Sun Mon ......
    1 1 200 100.....
    1 2 1000 NULL....
    I have tested the same using sum(decode...) method and also model clause:
    select grp1, grp2, sum(decode(day_week,'SUN',sales)) SUNDAY , sum(decode(day_week,'MON',sales)) MONDAY from pivot
    group by grp1, grp2
    order by grp1, grp2
    select grp1, grp2, sun , mon, tue, wed, thr, fri, sat
    from pivot
    model -- UNIQUE SINGLE REFERENCE
    return updated rows
    partition by (grp1, grp2)
    dimension by ( day_week)
    measures( result, 0 mon, 0 tue, 0 wed, 0 thr,0 fri, 0 sat, 0 sun)
    RULES upsert
    mon[0]= sales['MON'],
    tue[0]= sales['TUE'],
    wed[0]= sales['WED'],
    thr[0]= sales['THR'],
    fri[0]= sales['FRI'],
    sat[0]= sales['SAT'],
    sun[0]= sales['SUN']
    ) order by grp1, grp2
    There are 4K records in the table. The first query is taking app (.125 seconds) and the second query (.230 seconds).
    Pls tell how the model clause can give better performance and I want to use it for pivoting in all my APIs.
    Regards
    Rajiv

    > I read somewhere while searching on net.
    And now you can't find it anymore? I wouldn't believe anything you read somewhere while searching on net, unless it has some kind of proof attached.
    > You pls tell is it so or it depends upon volume of data.
    Also i tested on some data and reults were better in
    case of using normal startegy rather than model.(case
    provided above).
    So you have tested it yourself already. The model clause is great in a few cases (string aggregation, calculating values based on calculated values), but this doesn't seem to be one of them. On 11g you might want to consider the PIVOT operator.
    Regards,
    Rob.

  • 11g PIVOT uses static columns - why why why???

    I am very curios to know why we have to hard-code the "pivot in" clause in a pivot query. Does this not defeat the purpose of pivoting?
    we have to write this:
    SELECT *
    FROM (SELECT customer_id, product_code, quantity
    FROM pivot_test)
    PIVOT (SUM(quantity) AS sum_quantity FOR (product_code) IN ('A' AS a, 'B' AS b, 'C' AS c))
    ORDER BY customer_id;
    Why can we not put a subquery in the "IN" clause? Or even better, leave it blank to indicate we are pivoting for all.
    I know you can do something like this with the PIVOT XML function, but I want columns in the result, not XML. And I also do not want to build the query as a string and execute it like that, it gets really messy and I feel sorry for the next bloke who needs to take over from me.
    Does anybody know why this seems to not be possible for ORACLE?
    Thanks all.

    In addition to the excellent relational theory reasons the SQL standard (and relational database vendors) can't do dynamic pivots, there are important practical problems.
    Every API that interacts with any database (ODBC, JDBC, ODP.Net, ADO, DAO, OLE DB, OO4O, etc.) goes through a series of steps in order to execute a SQL statement.
    1) The statement is prepared.
    2) The bind variables are bound and return variables are created
    3) The statement is executed.
    Preparing the statement involves the database parsing the query (but not executing it). This provides the client with a statement handle that can be interrogated to, for example, describe the result set to expect. This allows the client to determine that, for example, a query is going to return 5 columns, the first of which is an integer and the next 4 of which are VARCHAR2(100)'s. The client then knows what data structures it needs to allocate. Since this statement handle is potentially going to be cached and reused many times with many different sets of bind variables, the structure of the result needs to be fixed.
    If a database permitted the structure of the query to change because data changed, it would cause massive havoc across every application that interacted with the database. You'd have to add something to every database API that allowed the database to come back from an attempt to execute a query and say "hey, I know I told you a while ago that this query was going to return 5 columns-- turns out, now it returns 6 (or 4 or 17)". Tons of code that relies on these APIs would need to be rewritten to be able to handle that exception, discard the cached handles, reallocate the data structures, re-execute the query, and figure out what, if any, downstream impacts that has on the application code. That would be a massive undertaking and would create much more work than would be saved by allowing a dynamic pivot.
    Justin

  • Reading filters fields in a pivot using vba

    Hi 
    I am able to store the Row Fields, Value Fields, Column Fields of a pivot. But if a filters are applied to a pivot.
    like Pivot.PivotFields, Pivot.RowFields, etc
    How can we read the what is the field applied for the filter fields?
    Thanks
    Sreeram
    Madhukar

    Hi,
    Please try the sample code, it'll read the filter field which you select:
    Sub Test()
    Dim pt As PivotTable
    Dim pf As PivotField
    Dim pi As PivotItem
    Set pt = Sheets("Scores").PivotTables(1)
    For Each pf In pt.PivotFields
    If pf.Orientation = xlPageField Then
    Debug.Print pf.Name
    For Each pi In pf.PivotItems
    If pi.Visible = True Then
    Debug.Print pi.Value
    End If
    Next
    End If
    Next pf
    End Sub
    PS: 
    This is the forum to discuss questions and feedback for Microsoft Excel, if you have any further question about Excel developer, please post the question to the MSDN forum for Excel
    http://social.msdn.microsoft.com/Forums/en-US/home?forum=exceldev&filter=alltypes&sort=lastpostdesc
    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.
    George Zhao
    TechNet Community Support
    It's recommended to download and install
    Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
    programs.

  • Pivot query problem

    All (running 11.2 on OEL 5),
    I am struggling figuring out how to get the result I want with the following data:
    CREATE TABLE REGION_LOOKUP
       (     REGION_ID NUMBER NOT NULL ENABLE,
         REGION VARCHAR2(5) NOT NULL ENABLE,
         PRIMARY KEY ("REGION_ID") ENABLE
    CREATE TABLE IND_REVENUE
       (     ID NUMBER,
         IND_REV_DATE VARCHAR2(30),
         IND_REVENUE NUMBER,
         REGION_ID NUMBER,
         CONSTRAINT IND_REVENUE_PK PRIMARY KEY (ID) ENABLE
    INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(1,'EMEA');
    INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(2,'LAD');
    INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(3,'APAC');
    INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(4,'NAS');
    INSERT INTO REGION_LOOKUP (REGION_ID, REGION VALUES(5,'JAPAN');
    INSERT INTO IND_REVENUE VALUES(1,'10-Jun',73.10,4);
    INSERT INTO IND_REVENUE VALUES(2,'10-Jul',49.30,4);
    INSERT INTO IND_REVENUE VALUES(3,'10-Jun',3.20,2);
    INSERT INTO IND_REVENUE VALUES(4,'10-Jul',0.30,2);
    INSERT INTO IND_REVENUE VALUES(5,'10-Jun',28.60,3);
    INSERT INTO IND_REVENUE VALUES(6,'10-Jul',12.40,3);
    INSERT INTO IND_REVENUE VALUES(7,'10-Jun',64.00,1);
    INSERT INTO IND_REVENUE VALUES(8,'10-Jul',19.80,1);
    INSERT INTO IND_REVENUE VALUES(9,'10-Jun',6.60,5);
    INSERT INTO IND_REVENUE VALUES(10,'10-Jul',4.70,5);
    /The result I'd like to get is as follows. The date column 10-Jun and 10-Jul is "dynamic" as there will be a new column every month.
    Region     10-Jun     10-Jul      Total
    APAC      $28.6     $12.4      $41.0
    EMEA      $64.0     $19.8      $83.8     
    JAPAN       $6.6      $4.7      $11.3
    LAD       $3.2      $0.3       $3.5
    NAS      $73.1     $49.3     $122.4
    Total     $175.5     $86.5     $262.0I am thinking something like this (I am stuck) but this obviously doesn't work at all and is also hard coded with regards to the columns.
    select rn, 10-Jun, 10-Jul, (10-Jun + 10-Jul) as Total from
    (select      RL.REGION_NAME as rn, RL.REGION as re, IR.IND_REVENUE as rev
    from      REGION_LOOKUP RL,
          IND_REVENUE IR where IR.region_id = RN.region_id)
    pivot (SUM(rev) for rn in
    ('10-Jun' as 10-Jun,
    '10-Jul' as 10-Jul))Any great ideas?
    Cheers,
    Andy
    Fixed the insert statements, sorry about that. Copy and paste before coffee isn't good.

    Hi, Andy,
    A Tael wrote:
    A nice solution, Thanks, but which solution do you mean? There were at least 4 different soltuions on that page.
    but isn't there a way to avoid the spooling into a file?Do you mean the dynamic SQL solution? Yes, SPOOLing is just one way to do dynamic SQL.
    In SQL*Plus you can write the variable part of the query to a substitution variable (see below).
    In PL/SQL, you can assemble a SELECT statement in VARCHAR2 variables.
    PROMPT     ==========  2. Dynamic Pivot using Substitution Variable  ==========
    --     *****  Preliminary Query:  *****
    COLUMN     sql_txt_col     NEW_VALUE     sql_txt
    WITH     all_jobs     AS
         SELECT DISTINCT
              job
         ,     DENSE_RANK () OVER (ORDER BY job)     AS r_num
         FROM     scott.emp
    SELECT     SYS_CONNECT_BY_PATH ( job || '''     THEN 1 END) AS '
                          || job
                          || '_CNT'
                          || CHR (10)               -- Newline, for legibility only
                       , ', COUNT (CASE WHEN job = '''     -- Delimiter, goes before each entry
                       )                                       AS sql_txt_col
    FROM     all_jobs
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     r_num = 1
    CONNECT BY     r_num = PRIOR r_num + 1
    --     *****  Main Query  *****
    SELECT     deptno
    &sql_txt     -- Ends with newline, so occupy that line
    FROM     scott.emp
    GROUP BY     deptno
    ORDER BY     deptno
    EXPLANATION:
    Using a substitution variable is very similar to using a script.
    The main difference is that the output of the preliminary query has to
    go into one row.  This is done with SYS_CONNECT_BY_PATH, and getting
    that requires that the jobs be numbered with consecutive integers, 1, 2, 3, ...
    which we get from DENSE_RANK.
    The NEWLINE character was added just to make the output line easier
    to read during debugging.
    */

  • Pivot function and Missing expression error

    select * from (
    select T.PAT_MRN_ID, T.ABBREVIATION,CONCEPT_VALUE from TBL_WORKLFOw T
    pivot
    max(concept_value)
    for ABBREVIATION in (select ABBREVIATION from TBL_WORKLFOW )
    this query is throwing "missing expression"..error.
    Can some one help figuring out the problem.

    Hi, Parth,
    Parth Divekar wrote:
    So your suggestion is to have it in a procedure ...form a dynamic sql using values from query and then execute the sql..That's one thing you can do.
    You might also look into string aggregation, where you have one gargantuan column containing all the pivoted data from all the abbreviatons, no matter how many there are. That big column can be formatted so that it looks like several distinct columns.
    Assuming dynamic SQL is the best answer, I find it easier to do in SQL*Plus, using files or substitution variables, as shown below. That's just my preference; you may like PL/SQL better.
    How to Pivot a Table with a Dynamic Number of Columns
    This works in any version of Oracle
    The "SELECT ... PIVOT" feature introduced in Oracle 11
    is much better for producing XML output.
    Say you want to make a cross-tab output of
    the scott.emp table.
    Each row will represent a department.
    There will be a separate column for each job.
    Each cell will contain the number of employees in
         a specific department having a specific job.
    The exact same solution must work with any number
    of departments and columns.
    (Within reason: there's no guarantee this will work if you
    want 2000 columns.)
    Case 0 "Basic Pivot" shows how you might hard-code three
    job types, which is exactly what you DON'T want to do.
    Case 1 "Dynamic Pivot" shows how get the right results
    dynamically, using SQL*Plus. 
    (This can be easily adapted to PL/SQL or other tools.)
    PROMPT     ==========  0. Basic Pivot  ==========
    SELECT     deptno
    ,     COUNT (CASE WHEN job = 'ANALYST'  THEN 1 END)     AS analyst_cnt
    ,     COUNT (CASE WHEN job = 'CLERK'    THEN 1 END)     AS clerk_cnt
    ,     COUNT (CASE WHEN job = 'SALESMAN' THEN 1 END)     AS salesman_cnt
    FROM     scott.emp
    WHERE     job     IN ('ANALYST', 'CLERK', 'SALESMAN')
    GROUP BY     deptno
    ORDER BY     deptno
    PROMPT     ==========  1. Dynamic Pivot using Script  ==========
    --     *****  Start of dynamic_pivot.sql  *****
    -- Suppress SQL*Plus features that interfere with raw output
    SET     FEEDBACK     OFF
    SET     PAGESIZE     0
    SPOOL     p:\sql\cookbook\dynamic_pivot_subscript.sql
    SELECT     DISTINCT
         ',     COUNT (CASE WHEN job = '''
    ||     job
    ||     ''' '     AS txt1
    ,     'THEN 1 END)     AS '
    ||     job
    ||     '_CNT'     AS txt2
    FROM     scott.emp
    ORDER BY     txt1;
    SPOOL     OFF
    -- Restore SQL*Plus features suppressed earlier
    SET     FEEDBACK     ON
    SET     PAGESIZE     50
    SPOOL     p:\sql\cookbook\dynamic_pivot.lst
    SELECT     deptno
    @@dynamic_pivot_subscript
    FROM     scott.emp
    GROUP BY     deptno
    ORDER BY     deptno
    SPOOL     OFF
    --     *****  End of dynamic_pivot.sql  *****
    EXPLANATION:
    The basic pivot assumes you know the number of distinct jobs,
    and the name of each one.  If you do, then writing a pivot query
    is simply a matter of writing the correct number of ", COUNT ... AS ..."\
    lines, with the name entered in two places on each one.  That is easily
    done by a preliminary query, which uses SPOOL to write a sub-script
    (called dynamic_pivot_subscript.sql in this example).
    The main script invokes this sub-script at the proper point.
    In practice, .SQL scripts usually contain one or more complete
    statements, but there's nothing that says they have to.
    This one contains just a fragment from the middle of a SELECT statement.
    Before creating the sub-script, turn off SQL*Plus features that are
    designed to help humans read the output (such as headings and
    feedback messages like "7 rows selected.", since we do not want these
    to appear in the sub-script.
    Turn these features on again before running the main query.
    PROMPT     ==========  2. Dynamic Pivot using Substitution Variable  ==========
    --     *****  Preliminary Query:  *****
    COLUMN     sql_txt_col     NEW_VALUE     sql_txt
    WITH     all_jobs     AS
         SELECT DISTINCT
              job
         ,     DENSE_RANK () OVER (ORDER BY job)     AS r_num
         FROM     scott.emp
    SELECT     SYS_CONNECT_BY_PATH ( job || '''     THEN 1 END) AS '
                          || job
                          || '_CNT'
                          || CHR (10)               -- Newline, for legibility only
                       , ', COUNT (CASE WHEN job = '''     -- Delimiter, goes before each entry
                       )                                       AS sql_txt_col
    FROM     all_jobs
    WHERE     CONNECT_BY_ISLEAF     = 1
    START WITH     r_num = 1
    CONNECT BY     r_num = PRIOR r_num + 1
    --     *****  Main Query  *****
    SELECT     deptno
    &sql_txt     -- Ends with newline, so occupy that line
    FROM     scott.emp
    GROUP BY     deptno
    ORDER BY     deptno
    EXPLANATION:
    Using a substitution variable is very similar to using a script.
    The main difference is that the output of the preliminary query has to
    go into one row.  This is done with SYS_CONNECT_BY_PATH, and getting
    that requires that the jobs be numbered with consecutive integers, 1, 2, 3, ...
    which we get from DENSE_RANK.
    The NEWLINE character was added just to make the output line easier
    to read during debugging.
    */

  • Error message when launching PowerPivot Window using Excel 2010

    I have installed the latest version of Powerpivot on several of our workstations.  Some of them are running the application just fine and some of them are getting an intermittent error message when trying to launch the PowerPivot Window.
    We are running Windows 7 ENT 32bit with Office 2010 32bit
    The error message given is : An operation that uses the database driver could not be completed.   If the driver is a Microsoft driver, make sure the drvier file isn't damaged, and if it is, reinstall the driver by re-installing Microsoft Query.  
    You can then try again and it will work.
    In fact the majority of the time this error message won't appear.
    The application has been removed and reinstalled.
    When I checked event viewer i'm finding this error which I think is related
    The description for Event ID 1 from source MSOLAP$LocalCube cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

    MSOLAP$LocalCube cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted.
    Hello,
    It's just a guess: Power Pivot uses the MSOLAP = "Microsoft OleDB Provider for OLAP" and maybe that Provider is damaged on the machine. You may try to reinstall the Provider, you can get the installer named "SQL_AS_OLEDB.msi" from
    Microsoft® SQL Server® 2012 SP2 Feature Pack  =>
    ENU\x86\SQL_AS_OLEDB.msi (for 32 bit)
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • PIVOT table in SQL?

    Hello,
    I have a table with 3 columns, where person_id is unique id.
    <person_id> <event_type> <number_events>
    1. I need to transform this into a table with <person_id> <event_type1> <event_type2>.... <event_type-n>
    And under each column I need to fill the number_events for each event_type for that person_id
    2. Next step is to use that table and convert the same into % of number_events under each event_type, as % of total number_events for each id_member
    Thanks

    1. I need to transform this into a table with <person_id> <event_type1> <event_type2>.... <event_type-n>Problem as a SQL projection cannot be of an-unknown-number-of-columns-we-will-figure-it-out-at-run-time. Unless you use some funky PL/SQL coding to create an Advance SQL Data Type that sports a RTTI interface. And this is typically t0o complex for the "normal" PL/SQL developer that almost never use Advance SQL Data Types to create SQL classes, never mind using OCI calls to define PL/SQL methods for RTTI interfaces.
    You can of course have a column that is a collection - and a collection can contain any number of elements.
    Example:
    SQL> -- create a collection type of strings
    SQL> create or replace type TStrings as table of varchar2(4000);
      2  /                                                         
    Type created.
    SQL>
    SQL> col TYPE format a15
    SQL> col NAME_LIST format a100
    SQL>                         
    SQL> -- now perform a pivot using a collection where
    SQL> -- the collection can be 1..n                 
    SQL> select                                        
      2          t.object_type as "TYPE",              
      3          cast(   multiset(                     
      4                          select object_name from user_objects n where n.object_type = t.object_type
      5                  )                                                                                
      6                  as TStrings                                                                      
      7          ) as "NAME_LIST",                                                                        
      8          count(*) as "TOTAL"                                                                      
      9  from       user_objects t                                                                        
    10  group by                                                                                         
    11          t.object_type                                                                            
    12  order by 1                                                                                       
    13  /                                                                                                
    TYPE            NAME_LIST                                                                                                 TOTAL
    FUNCTION        TSTRINGS('TESTPIPE', 'TO_TMINOR', 'TO_SUB', 'AUTHENTICATE', 'CHECKSUM', 'FOOPIPE', 'WEBBROWSER', 'PR         19
                    EVENTDELETE', 'GETSTAT', 'GETHOSTNAME', 'FOOFUNC', 'TOKENISE', 'DYNAMICFUNCTION', 'STATS', 'POP3', '          
                    CALC', 'VPDBPOLICY', 'LISTTONUMBERS', 'TCPPING')                                                              
    INDEX           TSTRINGS('SYS_C0046436', 'SYS_C0046439', 'SYS_IOT_TOP_125320', 'SYS_IOT_TOP_125322', 'SYS_IOT_TOP_12         23
                    5324', 'SYS_IOT_TOP_125327', 'PK_STUFF', 'SYS_C0055439', 'SYS_C0076868', 'PATIENT_PK', 'SYS_C0055021          
                    ', 'INPATIENT_PK', 'SYS_C0055023', 'BED_PK', 'PK_TAB11', 'PK_ROUTERS', 'SYS_C0055202', 'PK_FOO_TAB',
                     'PK_FOO_UPDATE', 'PK_SERIALISE', 'SYS_C0058353', 'PK_EMP', 'PK_ANYCHART_TEMPLATES')
    LIBRARY         TSTRINGS('LIBC')                                                                                              1
    LOB             TSTRINGS('SYS_LOB0000125313C00031$$', 'SYS_LOB0000153382C00007$$', 'SYS_LOB0000141150C00002$$', 'SYS          6
                     _LOB0000205530C00001$$', 'SYS_LOB0000197183C00002$$', 'SYS_LOB0000209404C00002$$')

  • How create animated power view reports using sharepoint list as a data source in sharepoint 2010?

    Hi All,
    I got a client requirement to create reports using SharePoint List as data source. The report should show reflection depends on values changed (I mean animation).
    I have heard about the power view/power pivot which does this kind of animations in reports.
    Can someone please guide me on creating reports which shows animations
    In power view/power pivot using SharePoint List as data source in SharePoint 2010.
    Thanks in advance.
    MercuryMan

    Hi MercuryMan,
    Yes, Power View, a feature of SQL Server 2012 Reporting Services Add-in for Microsoft SharePoint Server 2010 or SharePoint 2013 Enterprise Edition, is an interactive data exploration, visualization, and presentation experience.
    It provides multiple views featuring tiles, slicers, a chart filter, and a number of visualizations, including cards, small multiples, and a bubble chart. So, we can use Power View to do intuitive ad-hoc reporting for business users such as data analysts, business
    decision makers, and information workers.
    Currently, Power View report only supports two types of data models: PowerPivot Worksheet, and data models based on Analysis Services Tabular Model or Multidimensional Cube.
    In your scenario, you can create PowerPivot worksheets using SharePoint List as data source, deploy the PowerPivot worksheet to a SharePoint Library or PowerPivot Gallery, and then generate Power View reports based on the PowerPivot worksheets on the SharePoint
    site.
    To use SharePoint List as data source in Excel PowerPivot, you can refer to the following resource:
    http://blogs.technet.com/b/excel_services__powerpivot_for_sharepoint_support_blog/archive/2013/07/11/excel-services-using-a-sharepoint-list-as-a-data-source.aspx 
    http://technet.microsoft.com/en-us/library/hh230322.aspx 
    To create a Power View report based on PowerPivot model, you can refer to the following links:
    http://technet.microsoft.com/en-us/library/hh231522.aspx 
    http://technet.microsoft.com/en-us/library/hh759325.aspx 
    Regards,
    Mike Yin
    If you have any feedback on our support, please click
    here
    Mike Yin
    TechNet Community Support

  • For XML as PIVOT

    Thanks for reading.
    I need to export data via SQL to XML. But I need the XML format in Row/column and the output must be a Pivot table. I know that it can be done with AS pivot. But I don't know how to use it in the below script
    I've already got a fantastic script with the outcome in Row/Column format, but the output must be in pivot
    use Cluster_Data_Mart_NEW
    ;With CTE
    AS
    SELECT [Cluster_Name]
    ,[Cell_Name]
    ,[Client_Name]
    ,[Assigned]
    FROM CDM_Fact_Personnel_Assigned
    INNER JOIN CDM_Dim_Organization on
    CDM_Fact_Personnel_Assigned.Organization_Key =
    CDM_Dim_Organization.Organization_Key
    INNER JOIN CDM_Dim_Client on CDM_Fact_Personnel_Assigned.Client_Key =
    CDM_Dim_Client.Client_Key
    select
    select [Cluster_Name] AS [@name],
    (select [Cell_Name] as [column],
    null as tmp,
    Client_Name as [column],
    null as tmp,
    Assigned as [column]
    from CTE
    where [Cluster_Name] = t.[Cluster_Name]
    for xml path('row'),type) as [*]
    from (select distinct [Cluster_Name] from CTE)t
    for xml path('variable'),root('data')
    ) as col_xml
    the above query needs to be in the same XML format(Row/Clolumn) but then in a Pivot table structure.
    The desired outcome:
    ..............CellA...CellB
    companyA..4.......3
    companyB..0.......4
    companyC..1.......2
    (whithout the ..............)
    The desired outcome in XML:
    <data>
    <variable name="Cluster_Name">
    <row>
    <column></column>
    <column>CellA</column>
    <column>CellB</column>
    </row>
    <row>
    <column>companyA</column>
    <column>4</column>
    <column>3</column>
    </row>
    <row>
    <column>companyB</column>
    <column>0</column>
    <column>4</column>
    </row>
    <row>
    <column>companyC</column>
    <column>1</column>
    <column>2</column>
    </row>
    </variable>
    Is this possible?
    Thanks in advance.
    Regards,
    Bart

    Hi Russ,
    I
    get no error message anymore :) Only is the output not yet as desired.
    <data>
      <variable name="Cluster_Name">
        <row>
          <column />
          <column>CellA</column>
          <column>CellB</column>
        </row>
        <row>
          <column>Company1</column>
          <column>CellA</column>
          <column>CellB</column>
        </row>
        <row>
          <column>Company2</column>
          <column>CellA</column>
          <column>CellB</column>
        </row>
    The desired is the second and third rows need to be the value of the column "Assigned" Like:
    <data>
    <variable name="Cluster_Name">
    <row>
    <column></column>
    <column>CellA</column>
    <column>CellB</column>
    </row>
    <row>
    <column>companyA</column>
    <column>4</column>
    <column>3</column>
    </row>
    <row>
    <column>companyB</column>
    <column>0</column>
    <column>4</column>
    </row>
    <row>
    <column>companyC</column>
    <column>1</column>
    <column>2</column>
    Table1: CDM_Fact_Personnel_AssignedColumn1: [Assigned]                   -> its a number like: 2,3,4,6Table2: CDM_Dim_OrganizationColumn1: [Cluster_Name]               Column2: [Cell_Name]                  -> CellA, CellB
    Table3: CDM_Dim_Client Column1: [Client_Name]                -> CompannyA, CompannyB
    Thanks in advance
    Regards,
    Bart

  • The SQL statement is not valid - when importing data from SQL Server using a query

    Hi there,
    I am trying to import data from SQL to Power Pivot using a SQL query like below:
    SELECT Score.FieldCount, Score.Record.GetAt(0), Score.Record.GetAt(1),  Score.Record.GetAt(2),  Score.Record.GetAt(3),  Score.Record.GetAt(4)
    FROM 
    SELECT * FROM dbo.CLR1(
    dbo.CLR2('c:\FILES\Test.xml'), 
    'SELECT * FROM [dbo].[CXCustomer_Small]') Input
    ) Score
    And when I tried to validate it, it returns
    The SQL statement is not valid. A column name cannot be blank.
    I ran the above SQL statement in Management Studio and it works without problem. Any idea?
    Thanks!
    Chu
    -- Predict everything. http://www.predixionsoftware.com

    Never mind, I figured out - I need to give each column a name.
    -- Predict everything. http://www.predixionsoftware.com

  • Issue with sys_connect_by_path

    Hi all,
    Let me preface this post with I'm new to Oracle, using 10g, and mostly a self taught SQL person so it's not my strong suit. The overall goal is I'm trying to find folders within an area of our document management system that haven't been touched so we can perform some clean up. What I have to do is first find all active documents and its' parent folder in the hierarchy then compare the active folders to all folders to get my inactive folders. I have the first part of this working with the following:
    SELECT      Distinct(ActiveFolderID)
    FROM        (SELECT DataID, substr(sys_connect_by_path(DataID, '\'), instr(sys_connect_by_path(DataID, '\'),
                        '\', 1,2) + 1, instr(sys_connect_by_path(DataID, '\'), '\',1,3)
                        - instr(sys_connect_by_path(DataID, '\'), '\',1,2)-1) ActiveFolderID
                 FROM DTree
                 START WITH DataID = 9081729
                 CONNECT BY PRIOR DataID = ParentID) dt, DAuditNew da
    WHERE dt.DataID=da.DataID AND DA.PERFORMERID != 11681125 AND da.AuditDate > SysDate - 90Where I run into an issue is when I add the next part to select folders that aren't in the above result:
    SELECT      DataID, Name
    FROM        DTree
    WHERE       SubType=0 AND ParentID=9081729 AND DataID NOT IN (SELECT Distinct(ActiveFolderID)
                        FROM (SELECT DataID, substr(sys_connect_by_path(DataID, '\'), instr(sys_connect_by_path(DataID, '\'),
                                     '\', 1,2) + 1, instr(sys_connect_by_path(DataID, '\'), '\',1,3)
                                     - instr(sys_connect_by_path(DataID, '\'), '\',1,2)-1) ActiveFolderID
                              FROM DTree
                              START WITH DataID = 9081729
                              CONNECT BY PRIOR DataID = ParentID) dt, DAuditNew da
                        WHERE dt.DataID=da.DataID AND DA.PERFORMERID != 11681125 AND da.AuditDate > SysDate - 90)I get the following error:
    ORA-30004: when using SYS_CONNECT_BY_PATH function, cannot have seperator as part of column value
    30004. 00000 - "when using SYS_CONNECT_BY_PATH function, cannot have seperator as part of column value"
    *Cause:   
    *Action:   Use another seperator which does not occur in any column value,
    then retry.
    I know there are no \ in DataID as it a numeric field, but I have tried other seperators with no luck. Any ideas? Hopefully it's not something simple that I screwed up.
    Thanks,
    Bryan

    Hi, Byran,
    One way to get the results you want would be a MINUS operation. If I understand the requirements, you want
    (a) the set of all folders that are one level down from any node called 'root'
    MINUS
    (b) the subset of folders in (a) that have descendants whose names start with 'Activefile' and were audited no more than 90 days ago.
    We can get (a) with a self-join.
    We can get (b) with CONNECT BY, using (a) in the START WITH clause. In Oracle 9, we would have had to use SYS_CONNECT_BY_PATH for this, but starting in Oracle 10 we have CONNECT_BY_ROOT.
    WITH     top_level_folders     AS
         SELECT     c.dataid
         ,     c.name
         FROM     dtree     p
         JOIN     dtree     c  ON     c.parentid     = p.dataid
         WHERE     p.name     = 'root'
    ,     active_files     AS
         SELECT     CONNECT_BY_ROOT dataid     AS top_dataid
         ,     CONNECT_BY_ROOT name     AS top_name
         ,     dataid
         FROM     dtree
         WHERE     name     LIKE 'Activefile%'
         START WITH     dataid IN (
                             SELECT  dataid
                             FROM     top_level_folders
         CONNECT BY     parentid     = PRIOR dataid
    SELECT       dataid
    ,       name
    FROM       top_level_folders
         MINUS
    SELECT       af.top_dataid
    ,       af.top_name
    FROM       active_files     af
    JOIN       dauditnew     dan  ON     af.dataid     = dan.dataid
    WHERE       dan.auditdate     > SYSDATE - 90
    ORDER BY  dataid
    ;Output (when run on Feb. 2, 2012):
    `   DATAID NAME
             2 folder1
             3 folder2
             5 folder4As you can see, I did the filtering for audit dates near the end of the query. Depending on your data and your requirements, there might be a more efficient way to do it near the start of the query. The CONNECT BY is probably going to be the slow part of his job, so if there's some way to eliminate rows before that, it would probably be more efficient that running a longer CONNECT BY part, only to discard some of the results at the end. You don't want to do a join in the same sub-query as the CONNECT BY; that's extremely inefficient.
    I still have no idea why your original query was getting that ORA-30004 error. I'd be interested in finding out. I can't run the original query, apparantly because you simplified the tables for posting. If you can post a test case that gets the error using SYS_CONNECT_BY_PATH, I'll see if I can find out what caused it.

Maybe you are looking for

  • How to remove folder and leaf icons from a tree

    Hi, I know how to remove when we have a mx component i.e., <mx:Tree folderOpenIcon={null} ...../> similarly for closed and default leaf icon. But how do i achieve this from an action script like say i have, var tree:Tree = new Tree(); tree.setFolderO

  • Error in Operation Mapping for Idoc to File Scenario

    Hi Experts, I am doing Idoc to File Scenario for Timesheet IDoc "HRSM_C" and following step are through, Sender agreement --> Receiver Determination --> Interface Determination got stuck in Operation mapping, it sahows error "Unable to find resource

  • Nvidia - nouveau error

    Hi. I have installed archlinux and after some update I have nouveau error (X server is working fine anyway). that's the error: [ 7.014559] fb: conflicting fb hw usage nouveaufb vs VESA VGA - removing generic driver [ 7.014709] nouveau 0000:02:00.0: s

  • Opened FCP Clip In STP . . . Now How Do I Add Audio Tracks?

    I have opened an FCP 6 video clip in STP and the video and 2 audio tracks are facing me. I want to get rid of the clip's audio tracks and replace them with tracks on which I am going to create a musical background. I am not concerned about deleting t

  • Sub Dividing BIG Library into Small Ones..Scared to erase.

    I have a single 3tb Library after updating to 10.1 Im trying to now sort into smaller libraries.... Iv created new ones and MOVED Events and Projects into these libraries. ( I TICKED ON ...  Move Proxy and Optimized data.) Its still saying that the o