Pivot Query with Top N

Oracle 10g
I have formed the following query;
select cell
     , plot_number
     , max(decode(drnk, '1', tree_height*100)) ht_1
     , max(decode(drnk, '2', tree_height*100)) ht_2
     , max(decode(drnk, '3', tree_height*100)) ht_3
  from (select cell
             , plot_number
             , tree_height
             , drnk
          from (select cell
                     , plot_number
                     , tree_height
                     , dense_rank() over (partition by plot_number order by tree_height desc)drnk
                  from jip_recovery
         where drnk <= 3
           and tree_height is not null
         order by tree_height desc
group by cell, plot_number
order by cell, plot_numberThis query is supposed to take data like this and pivot it for the three tallest trees;
select cell, plot_number, tree_height from jip_recovery where cell = 'C01' and plot_number = 10151;
CELL PLOT_NUMBER            TREE_HEIGHT           
C01  10151                  14.01                 
C01  10151                  21.33                 
C01  10151                  16.06                 
C01  10151                  16.88                 
C01  10151                  18.29                 
C01  10151                  12.27                 
6 rows selected When I include a filter for CELL and PLOT NUMBER like this;
select cell
     , plot_number
     , max(decode(drnk, '1', tree_height*100)) ht_1
     , max(decode(drnk, '2', tree_height*100)) ht_2
     , max(decode(drnk, '3', tree_height*100)) ht_3
  from (select cell
             , plot_number
             , tree_height
             , drnk
          from (select cell
                     , plot_number
                     , tree_height
                     , dense_rank() over (partition by plot_number order by tree_height desc)drnk
                  from jip_recovery
                 where cell in ('C01')
                   and plot_number in (10151)
         where drnk <= 3
           and tree_height is not null
         order by tree_height desc)
group by cell, plot_number
order by cell, plot_numberIt returns the correct values in the three columns
CELL PLOT_NUMBER            HT_1                   HT_2                   HT_3                  
C01  10151                  2133                   1829                   1688                   But when I remove the filter to run it on the complete dataset some 546000 records it returns nulls for some of the HT_% columns. Of special interest in this example is the record for plot number 10151 and 10153.;
CELL PLOT_NUMBER            HT_1                   HT_2                   HT_3                  
C01  8198                   2652                   2105                   2075                  
C01  8199                   2338                   2107                   2012                  
C01  10151                                         2133                                         
C01  10153                                         1993                   1628                  
C01  10154                  2151                   2135                   1976
...Can anyone see what I am doing wrong?
Ben

Yes, you missed cell from the partition.

Similar Messages

  • 11G Pivot Query with Oracle EBS

    Hello all,
    We are trying to use the 11G pivot query function with data from Oracle E-Business Suite. We have an 11G database installed with our Oracle APEX. We cannot seem to get the pivot function to work. At a glance, would anyone be able to see any glaring errors in our syntax. I am not certain it is possible to provide test data so...
    We are trying to have column headings with the Period Names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as the dataset.
    When we run the sql we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
    Any help or insight would be greatly appreciated.
    select * from (
    select segment2, accounted_dr, period_name
    from gl_je_lines a, gl_code_combinations b
    where b.code_combination_id = a.code_combination_id
    and segment2 = '007751')
    pivot
    sum(accounted_dr)
    for period_name in ('SEP-08','OCT-08','NOV-08')
    group by segment2, period_name

    lilhelp wrote:
    Hello all,
    We are trying to use the 11G pivot query function with data from Oracle E-Business Suite. We have an 11G database installed with our Oracle APEX. We cannot seem to get the pivot function to work. At a glance, would anyone be able to see any glaring errors in our syntax. I am not certain it is possible to provide test data Why not?
    >
    We are trying to have column headings with the Period Names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as the dataset.
    When we run the sql we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
    Any help or insight would be greatly appreciated.
    select * from (
    select segment2, accounted_dr, period_name
    from gl_je_lines a, gl_code_combinations b
    where b.code_combination_id = a.code_combination_id
    and segment2 = '007751')
    pivot
    sum(accounted_dr)
    for period_name in ('SEP-08','OCT-08','NOV-08')
    group by segment2, period_nameDon't use GROUP BY. When you use PIVOT, the grouping is implied by what is in the PIVOT clause and what is not.
    Try this:
    select    *
    from        (
           select  segment2
           ,       accounted_dr
           ,       period_name
           from       gl_je_lines          a
           ,       gl_code_combinations     b
           where       b.code_combination_id = a.code_combination_id
           and       segment2 = '007751'
    pivot       (
           sum (accounted_dr)
           for period_name in ('SEP-08','OCT-08','NOV-08')
    ;which is just your posted query without the GROUP BY clause.

  • 11G Pivot Query with parameters

    Hello all,
    I would like to find some way, any way to pass parameters to a pivot query. The following pivot query works, but I would like segment2 to be a variable as well as the period names so....
    select * from
    select segment2, accounted_dr, period_name
    from gl_je_lines a, gl_code_combinations b
    where b.code_combination_id = a.code_combination_id
    and segment2 >='007611' and segment2 <='007751' AND period_name in ('SEP-08','OCT-08','NOV-08'))
    pivot
    sum(accounted_dr)
    for period_name in ('SEP-08','OCT-08','NOV-08') )
    ....would be something like....
    select * from
    select segment2, accounted_dr, period_name
    from gl_je_lines a, gl_code_combinations b
    where b.code_combination_id = a.code_combination_id
    and segment2 >= :P4_OBJECT_FROM AND and segment2 <=:P4_OBJECT_TO AND period_name in &P4_EPSB_PERIOD_HOLD.)
    pivot
    sum(accounted_dr)
    for period_name in (&P4_EPSB_PERIOD_HOLD.) )
    It is our understanding that we have to hardcode period names and objects, but we would like to get around that. Does anyone have any ideas or tricks?
    Thanks

    lilhelp wrote:
    Hello all,
    We are trying to use the 11G pivot query function with data from Oracle E-Business Suite. We have an 11G database installed with our Oracle APEX. We cannot seem to get the pivot function to work. At a glance, would anyone be able to see any glaring errors in our syntax. I am not certain it is possible to provide test data Why not?
    >
    We are trying to have column headings with the Period Names SEP-08 OCT-08 NOV-08, with rows of segment2 007751 and accounted_dr as the dataset.
    When we run the sql we get an error ORA-00904: "PERIOD_NAME": invalid identifier.
    Any help or insight would be greatly appreciated.
    select * from (
    select segment2, accounted_dr, period_name
    from gl_je_lines a, gl_code_combinations b
    where b.code_combination_id = a.code_combination_id
    and segment2 = '007751')
    pivot
    sum(accounted_dr)
    for period_name in ('SEP-08','OCT-08','NOV-08')
    group by segment2, period_nameDon't use GROUP BY. When you use PIVOT, the grouping is implied by what is in the PIVOT clause and what is not.
    Try this:
    select    *
    from        (
           select  segment2
           ,       accounted_dr
           ,       period_name
           from       gl_je_lines          a
           ,       gl_code_combinations     b
           where       b.code_combination_id = a.code_combination_id
           and       segment2 = '007751'
    pivot       (
           sum (accounted_dr)
           for period_name in ('SEP-08','OCT-08','NOV-08')
    ;which is just your posted query without the GROUP BY clause.

  • Query with Top N Condition (Result Row)

    Hi,
    I made a query with an active top n condition. The query has 2 Keyfigures and 1 formula
    Gross-sales acutal | Gross-sales previous year | Previous Year %
    So that to result line is correct, I had to say "Calculate result as summation" for the keyfigures
    gross sales actual and gross sales previous year. That works.
    I have the problem with my formula. the formular for previous year % is defined as follows:
    gross sales actual %A gross sales previous year
    Example Top 3 Customer
                        gross sales actual          gross sales prev. year         prev. year %
    Cust 1          100                                   80                                       125 %
    Cust 2          90                                     45                                        200 %
    Cust 3           80                                    60                                        133 %
    Result          270                                   185                                       142.8 % ( 350 * 100 / 245 )
    The result of 142 % is the correct result without the condition top 3. with the top 3 condition
    the result should be 270 * 100 / 185 = 145.9 %
    Additional customer without top 3 condition
    Cust 4          50                                       40                                        125 %
    Cust 5          30                                        20                                        150 %
    It shows the correct result for each single line. The result in the result row is wrong. it is calculated
    without taking the active condition. the formular calculates
    with the total gross sales actual and the total of gross sales prev. year.
    is there any solution the achieve the correct % in the result row?
    thanks for your help.
    Pascal

    Pascal,this is a known behavior with conditions.When you apply condition it just hide the extra rows and it does not impact the result row.So your result row actually shows the value irrespective of the condition you apply.
    Now with the help of local functions like calculate result as summation you can show the correct sum after applying the condition but when you try to use that result in some calculation then it takes the original value thereby discarding the calculated value.
    Same is happening in your case as well.Its taking the original value i.e 350 and not the calculated sum after condition i.e 270.
    Hope this helps.
    Regards,
    AL

  • Create  query with top 5 and rest

    Hi,i want to have a query that gives a list in the following format
    customer  - value of orders
    #1            -  20.500
    #2            -  20.100
    #3            -  16.000
    #4            -  15.000
    #5            -  14.000
    Rest         -  49.600
    how can i achieve that in a convenient way  - filters,conditions,exceptions,properties etc - all those new stuff?
    (i am new to BI,so excuse my beginners question,please)

    Hi,i am not sure if it is possible to diaply Value of Rest with standard functionality.Instead you can display Overall result.
    Create a condition TOP N and speify the number as 5. and make sure Suppress Result rows of Customer is set to 'never'.So you will get displayed Top 5 Customers and Overall result.
    if you are saving the result as WorkBook,then add one more Row after Query result to display result  with the Excel formula Overall Result-Top 5.Save the Workbook.

  • Power Pivot Bug: Can't Save Edits to Power Pivot Query without checking Teradata Connection's "Save my password" Option

    Can't edit and re-Save Power Pivot query with Teradata connection (using LDAP security mechanism) unless "Save my password" option was checked.  Without this option I receive this error upon attempt to Save changes made to the query ...
    The following exception occurred while the managed IDbConnection interface was being used: [TeraGSS Security Library] [115022] Exception occurred in TERAGSS layer.  See inner exception for details.;TdgssAuthenticationTokenExchange delegate threw an exception.
     See the inner exception for details.
    ErrorCode: -452984642 Severity: Error Facility: DotNet
    [Teradata Database] [8017] The UserId, Password or Account is invalid..
    A connection could not be made to the data source with the DataSourceID of '6a06124c-496f-4887-bf39-d2582173d499', Name of 'Teradata fsltdprd'.
    An error occurred while processing table 'Query'.
    The current operation was cancelled because another operation in the transaction failed.

    Sorry you're right, the Office category isn't currently accepting bug reports in which case Olaf's suggestion to use the smiley face is the way to go. In Excel please go to File > Options > Trust Centre > 'Trust Centre Settings...' and check
    that the Feeeback Tool is enabled.
    If the option is greyed out like this...
    ... then you should be able to enable it by changing the value of the 'Enabled' registry key from a 0 to a 1 which you will find under: HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Common\Feedback. You will then need to close all Office applications
    and re-launch Excel 2013.
    Once the Feeback Tool has been enabled, you should see the smile face(s) in the top right hand corner of the Excel window and be able to send your feedback.
    Regards,
    Michael
    Please remember to mark a post that answers your question as an answer...If a post doesn't answer your question but you've found it helpful, please remember to vote it as helpful :)
    Website: nimblelearn.com, Blog:
    nimblelearn.com/blog, Twitter:
    @nimblelearn

  • Query with a condition - Overall results row displays incorrect value

    Hi All,
    I have a bw query with top 40 conditions. However, The Overall Result Row Figures Do Not Equal The Sum of the Column Rows.
    Although the top condition is activated, the overall result still displays the overall result of the whole report.
    I have 3 columns in the report
    Selected Period
    Prior Period and
    Variance
    The formula for variance is (Selected Period/Prior Period)-1.
    Does anyone have an idea to fix this?
    Thank you so much in advance.
    Have a great day!

    Hi Gaurav,
    Thank you so much for your reply, however this does not solve fully the issue.
    Changing the properties to "Summation" will indeed provide me with the correct sum for the "selected period" and "Prior Period." However what I need in the Overall Result Row for the "Variance" column is not the total but instead the value when the total of Selected Period is divided by Prior Period then minus 1.
    Overall Variance = (Overall Selected Period/Overall Prior Period)-1
    Do you know a way to make this possible.
    Thank you so much.

  • Having a problem with writing pivoting query.

    Hi All,
    I have a query with one input parameter. It gives different result based on the input provided.
    For example
    1. If i give input as date1 the output would be as follows.
    Col1     Col2     Col3
    name1     v1     10
    name1     v2     14
    name2     v1     15
    name3     v3     202. If i give input as date2 the output would be as follows.
    Col1     Col2     Col3
    name2     v1     14
    name2     v2     10
    name3     v1     8
    name3     v2     14
    name1     v1     10
    name1     v2     34
    name1     v4     23
    name1     v5     10
    name4     v1     12
    name4     v2     14
    name4     v4     18
    name4     v5     20
    name5     v1     14
    name5     v2     10and so on for diff inputs, I get diff output.
    Now, I am trying to write a query which would give me the pivot data on the outputs shown above.
    For Example
    1. For the first output on the top, the pivot query should return the data as follows:
          name1     name2     name3
    v1     10     15     0
    v2     14     0     0
    v3     0     0     202. For the second output on the top, the pivot query should return the data as follows:
          name1     name2     name3     name4     name5
    v1     10     14     8     12     14
    v2     34     10     14     14     10
    v3     0     0     0     0     0
    v4     23     0     0     18     0
    v5     10     0     0     20     0and so on...
    I would be greatly thankful for any kind of input provided since.
    Regards
    Sapan

    Hi Frank,
    Thanks for your response, I did have a look at the thread which had the options for both static as well as the dynamic pivoting.
    But as you said this scenario needs a dynamic SQL. The only constraint is, I need to plug in the SQL into HTML-DB and spooling would not be feasible. That's the reason I am trying to frame a query around the current query which gives me the base data to be pivoted. I am also keeping my options open on coming up with PL/SQL block, which can integrate well with HTML-DB.
    Any thoughts/suggestions would be helpful.
    Thank you.

  • Select query with pivot

    Hi All,
    I have written a query as belows: but I dont get the output as desired.
    This is a with query -  I need the query output in a single record so I have pivoted the first query spl. The second set of query stk gives me the stock.
    My requirement is whnever there is a not matching mmg_id of 1st query with mmg5_id of 2nd query it should give the second record as follows
    LOC_LOC_ID      MMG_ID     TP_TP_ID      'S10'       'O3'            'O7'            'O8'       CN_STK_QTY      CN_STK_VAL
    1097                  1610           20132123       207.5      62.08       7504           25.06      603                       93027.5
    1097                  0024          20132123                                                                    -1                        -15.99
    {code}
    Connected to Oracle Database 11g Enterprise Edition Release 11.2.0.2.0
    Connected as sizsupport
    SQL>
    SQL> WITH spl AS
      2  (
      3  SELECT * FROM
      4  (SELECT '1097' loc_loc_id, '1610' mmg_id, '20132123' tp_tp_id, 'S10' measure_name,'207.5' val FROM dual UNION ALL
      5  SELECT '1097' , '1610' , '20132123' , 'O3' measure_name, '62.08'  FROM dual UNION ALL
      6  SELECT '1097' , '1610' , '20132123' , 'O7' measure_name, '7504'  FROM dual UNION ALL
      7  SELECT '1097' , '1610' , '20132123' , 'O8' measure_name, '25.06'  FROM dual )
      8  pivot ( sum(val) FOR measure_name IN
      9  ('S10','O3','O7','O8'))
    10  ),
    11  stk AS
    12  (
    13  SELECT '1097' loc_loc_id, '0024' mmg5_id, '20132123' tp_tp_id, '-1' cn_stk_qty, '-15.99' cn_stk_val FROM dual
    14  UNION ALL
    15  SELECT '1097' loc_loc_id, '1610' mmg5_id, '20132123' tp_tp_id, '603' cn_stk_qty, '93027.5' cn_stk_val FROM dual
    16  )
    17  SELECT spl.*,stk.cn_stk_qty,stk.cn_stk_val
    18  FROM spl  RIGHT OUTER JOIN stk
    19  ON spl.loc_loc_id = stk.loc_loc_id
    20  AND spl.tp_tp_id  = stk.tp_tp_id
    21  AND spl.mmg_id    = stk.mmg5_id
    22  ;
    LOC_LOC_ID MMG_ID TP_TP_ID      'S10'       'O3'       'O7'       'O8' CN_STK_QTY CN_STK_VAL
    1097       1610   20132123      207.5      62.08       7504      25.06 603        93027.5
                                                                           -1         -15.99
    SQL>
    {code}

    Hi,
    When there is no match between stk and spl, then all columns from spl will be NULL, but the values from stk will be available.  Take the columns you need to display from stk, not from spl.
    WITH  spl  AS
        SELECT  *
        FROM    raw_data
        PIVOT   (   SUM (val)
                FOR measure_name IN ( 'S10' AS s10
                                    , 'O3' AS p_03
                                    , 'O7' AS p_07
                                    , 'O8' AS p_08
    SELECT  stk.loc_loc_id
    ,       stk.mmg5_id
    ,       stk.tp_tp_id
    ,       spl.s10
    ,       spl.p_03
    ,       spl.p_07
    ,       spl.p_08
    ,       stk.cn_stk_qty
    ,       stk.cn_stk_val
    FROM             stk
    LEFT OUTER JOIN  spl  ON   spl.loc_loc_id = stk.loc_loc_id
                          AND  spl.tp_tp_id   = stk.tp_tp_id
                          AND  spl.mmg_id     = stk.mmg5_id
    I gave the pivoted columns standard names, like s10 and p_03.  You don't have to do that; you can use "'S10'" and "'P_03'" if you prefer.

  • SQL Query for TOP 10 Average CPU

    Have a SCOM Report request for a line graph showing top 10 average CPU for a group of servers. I have a query that will show all of the servers in a group for the last day, with the average CPU by hour. How can I extend the SQL query to only select the TOP
    10 average CPU from the group? Here is the Query I have:
    SELECT
    vPerf.DateTime,
    vPerf.SampleCount,
    cast(vPerf.AverageValue as numeric(10,2)) as AverageCPU,
    vPerformanceRuleInstance.InstanceName,
    vManagedEntity.Path,
    vPerformanceRule.ObjectName,
     vPerformanceRule.CounterName
    FROM Perf.vPerfHourly AS vPerf INNER JOIN
     vPerformanceRuleInstance ON vPerformanceRuleInstance.PerformanceRuleInstanceRowId = vPerf.PerformanceRuleInstanceRowId INNER JOIN
     vManagedEntity ON vPerf.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId INNER JOIN
     vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId
    WHERE
    vPerf.DateTime  >= DATEADD(Day, -1, GetDate())
    AND vPerformanceRule.ObjectName like '%Processor Information%'
    AND vPerformanceRuleInstance.InstanceName = '_Total'
    AND (vPerformanceRule.CounterName IN ('% Processor Time'))
    AND (vManagedEntity.Path IN (SELECT dbo.vManagedEntity.Name
    FROM dbo.vManagedEntity INNER JOIN
    dbo.vRelationship On dbo.vManagedEntity.ManagedEntityRowId = dbo.vRelationship.TargetManagedEntityRowId INNER JOIN
    dbo.vManagedEntity As CompGroup On dbo.vRelationship.SourcemanagedEntityRowId = CompGroup.ManagedEntityRowId
    WHERE CompGroup.DisplayName = 'bemis ibb prod'
    ORDER BY path, vPerf.DateTime
    Results
    DateTime
    SampleCount
    AverageCPU
    InstanceName
    Path
    ObjectName
    CounterName
    2/26/15 3:00 PM
    2
    1.98
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 4:00 PM
    2
    2.09
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 5:00 PM
    2
    1.72
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    2/26/15 6:00 PM
    2
    1.83
    _Total
    servername.corp.com
    Processor Information
    % Processor Time
    Thanks in Advance!
    Mike Hanlon

    Hi 
    Sql Query
    SELECT TOP 10
    vPerf.DateTime,
    vPerf.SampleCount, 
    cast(vPerf.AverageValue as numeric(10,2)) as AverageCPU,
    vPerformanceRuleInstance.InstanceName, 
    vManagedEntity.Path, 
    vPerformanceRule.ObjectName, 
     vPerformanceRule.CounterName
    FROM Perf.vPerfHourly AS vPerf INNER JOIN
     vPerformanceRuleInstance ON vPerformanceRuleInstance.PerformanceRuleInstanceRowId = vPerf.PerformanceRuleInstanceRowId
    INNER JOIN
     vManagedEntity ON vPerf.ManagedEntityRowId = vManagedEntity.ManagedEntityRowId INNER JOIN
     vPerformanceRule ON vPerformanceRuleInstance.RuleRowId = vPerformanceRule.RuleRowId 
    WHERE 
    vPerf.DateTime  >= DATEADD(Day, -1, GetDate())
    AND vPerformanceRule.ObjectName like '%Processor Information%'
    AND vPerformanceRuleInstance.InstanceName = '_Total'
    AND (vPerformanceRule.CounterName IN ('% Processor Time'))
    AND (vManagedEntity.Path IN (SELECT dbo.vManagedEntity.Name
    FROM dbo.vManagedEntity INNER JOIN
    dbo.vRelationship On dbo.vManagedEntity.ManagedEntityRowId = dbo.vRelationship.TargetManagedEntityRowId INNER
    JOIN
    dbo.vManagedEntity As CompGroup On dbo.vRelationship.SourcemanagedEntityRowId = CompGroup.ManagedEntityRowId
    WHERE CompGroup.DisplayName = 'bemis ibb prod'
    ORDER BY path, vPerf.DateTime
    Regards
    sridhar v

  • Getting counts and divide by sum in a single Pivot query

    Hi,
    I have a pivot query which gives the counts of all codes. I also have to divide the count with the total in the same query.
    e.g
      col1          col2                   col3
    error_1       05-Jun-2012       parts
    error_1      05_june_2012     parts
    error_1      04_june_2012     consumables
    error_2      04_june_2012     consumables
    error_3      03_june_2012     parts
    .Now the output should have the counts/divided by sum multiplied by 100. Basically, the percentage.
    output will be something like
    error                     June-2012                                 May-2012                              Feb-2012 ....      headers
    error_1                    60%                                          0 %                                         0%
    error_2                    20%                                          0                                             0%
    error_3                    20%                                           0%                                         0%Any suggestions please?
    Thanks,
    Sun

    with
    t1 as
    (select 'error_1' col1,trunc(sysdate) - 1 col2 from dual union all
    select 'error_1',trunc(sysdate) - 1 from dual union all
    select 'error_1',trunc(sysdate) + 30 from dual union all
    select 'error_2',trunc(sysdate) + 31 from dual union all
    select 'error_3',trunc(sysdate) - 2 from dual union all
    select 'error_3',trunc(sysdate) + 30 from dual union all
    select 'error_1',trunc(sysdate) - 3 from dual union all
    select 'error_2',trunc(sysdate) - 2 from dual union all
    select 'error_3',trunc(sysdate) + 30 from dual union all
    select 'error_4',trunc(sysdate) - 6 from dual
    select col1,
           count(case to_char(col2,'mon') when 'jul' then 1 end) one,
           100 * ratio_to_report(count(case to_char(col2,'mon') when 'jul' then 1 end)) over () x,
           count(case to_char(col2,'mon') when 'jun' then 1 end) two,    
           100 * ratio_to_report(count(case to_char(col2,'mon') when 'jun' then 1 end)) over () y
      from t1
    group by col1
    order by col1Regards
    Etbin
    Edited by: Etbin on 8.6.2012 14:15
    used next month to keep english and slovenian 'mon' the same ;)

  • Issue with SQL Query with Presentation Variable as Data Source in BI Publisher

    Hello All
    I have an issue with creating BIP report based on OBIEE reports which is done using direct SQL. There is this one report in OBIEE dashboard, which is written using direct SQL. To create the pixel perfect version of this report, I am creating BIP data model using SQL Query as data source. The physical query that is used to create OBIEE report has several presentation variables in its where clause.
    select TILE4,max(APPTS), 'Top Count' from
    SELECT c5 as division,nvl(DECODE (C2,0,0,(c1/c2)*100),0) AS APPTS,NTILE (4) OVER ( ORDER BY nvl(DECODE (C2,0,0,(c1/c2)*100),0))  AS TILE4,
    c4 as dept,c6 as month FROM 
    select sum(case  when T6736.TYPE = 'ATM' then T7608.COUNT end ) as c1,
         sum(case  when T6736.TYPE in ('Call Center', 'LSM') then T7608.CONFIRMED_COUNT end ) as c2,
         T802.NAME_LEVEL_6 as c3,
         T802.NAME_LEVEL_1 as c4,
         T6172.CALENDARMONTHNAMEANDYEAR as c5,
         T6172.CALENDARMONTHNUMBERINYEAR as c6,
         T802.DEPT_CODE as c7
    from
         DW_date_DIM T6736 /* z_dim_date */ ,
         DW_MONTH_DIM T6172 /* z_dim_month */ ,
         DW_GEOS_DIM T802 /* z_dim_dept_geo_hierarchy */ ,
         DW_Count_MONTH_AGG T7608 /* z_fact_Count_month_agg */
    where  ( T802.DEpt_CODE = T7608.DEPT_CODE and T802.NAME_LEVEL_1 =  '@{PV_D}{RSD}' 
    and T802.CALENDARMONTHNAMEANDYEAR = 'July 2013'
    and T6172.MONTH_KEY = T7608.MONTH_KEY and T6736.DATE_KEY = T7608.DATE_KEY
    and (T6172.CALENDARMONTHNUMBERINYEAR between substr('@{Month_Start}',0,6)  and substr('@{Month_END}',8,13))
    and (T6736.TYPE in ('Call Center', 'LSM')) )
    group by T802.DEPT_CODE, T802.NAME_LEVEL_6, T802.NAME_LEVEL_1, T6172.CALENDARMONTHNAMEANDYEAR, T6172.CALENDARMONTHNUMBERINYEAR
    order by c4, c3, c6, c7, c5
    ))where tile4=3 group by tile4
    When I try to view data after creating the data set, I get the following error:
    Failed to load XML
    XML Parsing Error: mismatched tag. Expected: . Location: http://172.20.17.142:9704/xmlpserver/servlet/xdo Line Number 2, Column 580:
    Now when I remove those Presention variables (@{PV1}, @{PV2}) in the query with some hard coded values, it is working fine.
    So I know it is the PV that's causing this error.
    How can I work around it?
    There is no way to create equivalent report without using the direct sql..
    Thanks in advance

    I have found a solution to this problem after some more investigation. PowerQuery does not support to use SQL statement as source for Teradata (possibly same for other sources as well). This is "by design" according to Microsoft. Hence the problem
    is not because different PowerQuery versions as mentioned above. When designing the query in PowerQuery in Excel make sure to use the interface/navigation to create the query/select tables and NOT a SQL statement. The SQL statement as source works fine on
    a client machine but not when scheduling it in Power BI in the cloud. I would like to see that the functionality within PowerQuery and Excel should be the same as in Power BI in the cloud. And at least when there is a difference it would be nice with documentation
    or more descriptive errors.
    //Jonas 

  • Dynamic SQL and Pivot Query in 11G

    Hello all,
    I am using APEX and 11G I am trying to create a report based on the results of a pivot query. Below is the code to build the query string. The :P4_EPSB_PERIOD_HOLD holds data like (SEP-08') for example.
    declare
    q varchar2(4000);
    begin
    q:=q ||' select * FROM';
    q:=q ||' ( ';
    q:=q ||' select segment2, ';
    q:=q ||' accounted_dr, ';
    q:=q ||' period_name ';
    q:=q ||' from gl_je_lines a, ';
    q:=q ||' gl_code_combinations b';
    q:=q ||' where b.code_combination_id = a.code_combination_id';
    q:=q ||' and segment2 >= :P4_EPSB_OBJECT_FROM';
    q:=q ||' and segment2 <= :P4_EPSB_OBJECT_TO';
    q:=q ||' and period_name IN :P4_EPSB_PERIOD_HOLD';
    q:=q ||' and segment4 >= :P4_EPSB_LOCATION_FROM';
    q:=q ||' and segment4 <= :P4_EPSB_LOCATION_TO';
    q:=q ||' )';
    q:=q ||' PIVOT';
    q:=q ||' (';
    q:=q ||' sum(accounted_dr)';
    q:=q ||' for period_name IN :P4_EPSB_PERIOD_HOLD';
    q:=q ||' )';
    return q;
    end;
    I get the missingfailed to parse SQL query:
    ORA-00906: missing left parenthesis
    If I print the sql statement that the query generates, I get the following code, which, if the varaibles are hard-coded, works fine.
    select * FROM ( select segment2, accounted_dr, period_name from gl_je_lines a, gl_code_combinations b where b.code_combination_id = a.code_combination_id and segment2 >= :P4_EPSB_OBJECT_FROM and segment2 <= :P4_EPSB_OBJECT_TO and period_name IN :P4_EPSB_PERIOD_HOLD and segment4 >= :P4_EPSB_LOCATION_FROM and segment4 <= :P4_EPSB_LOCATION_TO ) PIVOT ( sum(accounted_dr) for period_name IN :P4_EPSB_PERIOD_HOLD )
    Any advice as to how to tackle this would be most welecome and appreciated.
    Thanks

    P4_EPSB_PERIOD_HOLDcome with single quotes? like 'SEP-08' or SEP-08

  • How to find bottleneck in pivot query

    I have the following table and query I am running against that table.
    CREATE TABLE StagingTable(
    DateKey int NOT NULL,
    VersionNumber smallint NOT NULL,
    SetID varchar(10) NULL,
    ClassID char(5) NULL,
    VariableName varchar(50) NULL,
    VariableDescription varchar(255) NULL,
    PeriodNumber int NULL,
    PeriodData decimal(18, 6) NULL,
    Column1 varchar(50) NULL,
    Column2 varchar(50) NULL,
    Column3 varchar(50) NULL,
    Column4 varchar(50) NULL,
    Column5 int NULL,
    Column6 varchar(25) NULL,
    Column7 int NULL,
    Column8 int NULL,
    Column9 varchar(50) NULL,
    Column10 varchar(50) NULL,
    Column11 varchar(50) NULL,
    Column12 int NULL,
    RowNumber int NULL
    GO
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    CREATE UNIQUE NONCLUSTERED INDEX IX_StagingTable ON dbo.StagingTable
    DateKey,
    VersionNumber,
    SetId,
    ClassID,
    VariableName,
    PeriodNumber
    INCLUDE ([PeriodData])
    I have about 5 million rows in StageTable and the pivot query returns 32,000 rows.  It takes about 3 and a half minutes to run this query, whether I am outputting the results to the results window in SSMS or selecting into a new table.
    I checked the execution plan for this query (outputting to results window) and the only operation that takes any time is the non-clustered index scan (84% with Stream aggregate showing 14%).
    Here are the things I compared this to.  I ran a select from this table using just the columns in the index. The results returned in less than one minute and as expected the most expensive operation (100%) was the non-clustered index scan. 
    By the way, a select into returned almost immediately.
    If I take the pivot results (after a select into) and create a new table by select into, it takes almost no time for the query to finish.
    I did an estimated execution plan on these three queries (where PivotTable is a dump of the pivot query into a heap):
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    SELECT * from PivotTable;
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable;
    The first query (pivot query) had a cost of 41%, the second 25% (select pivottable) and the third 34% (select base table).  These are nowhere close to the ratios of the amount of time that it takes to run these queries (pivot query 3.5 minutes,
    select  PivotTable 5 seconds and select base table almost one minute).
    For the following:
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    into newTable1
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    SELECT *
    into newTable2
    from PivotTable;
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    into newTable3
    from StagingTable;
    The distribution of query cost is strikingly different.  The pivot query has a cost of 98% and the other two queries have costs of 1%.  The big difference between these queries and the versions that just output the results (in the execution plan)
    is in the table insert.  The pivot query shows a cost of 26,000 while the select from pivottable shows cost of 160 and select from StagingTable shows cost of 280.
    What else can I look at?  Also, what else can I try to optimize the pivot query.
    For now, I am going to see if I get better performance letting SSRS do the pivoting.
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

    I have finally nailed down what is causing the bottleneck.
    The Compute Scalar step for some reason shows almost no cost to the execution plan.  But I noticed that the actual number of rows is 5 million (the same as the scan).  It appears that SQL Server expands every row to 360+ columns, all 5 million
    of them.
    So I did an experiment.  I took the table that I was populating and did a cross join to a number table.  This table has 30 K rows and 360 columns.  I figured that if I select 150 rows from the number table it will generate around 5 million
    rows.  The results were almost identical to using the MAX(CASE WHEN ...) construct:  1 minute and some change.
    I then cross joined with only 75 rows.  It took 30 seconds.  37 rows took about 15 seconds.
    So the Compute Scalar costs a lot more then the Execution plan analyzer says.
    SSIS appears to gather one row at a time.  Once it finishes one row, one group by set, it sends the row on its way.  So, in my case, the 5 million rows is read in with 7 columns and 30 K rows are output with 365 columns or so.
    SQL Server creates 5 million rows with 365 columns, then aggregates them down to 30 K rows.
    Thank you, Tom for you discussion with me on this.  I think that I can present my thoughts to my lead.
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

  • How to write XSJS Select Query with input parameters

    Hello Experts,
    I am creating a xsjs file and in that file I am trying to write a Select Query based on a Calculation View
    I have tried it the following way:
    var query = 'SELECT TOP 100 \"Name\", \"Address\", \"City\", \"Country\" FROM \"_SYS_BIC\".\"Test.HL/AddressView\"'
        + 'WITH PARAMETERS(\'PLACEHOLDER\' = (\'$$P_Name$$\', \' Akhil \'),'
      + '\'PLACEHOLDER\' = (\'$$P_City$$\', \' Lucknow \'))';
    But it gives me the "Mixed spaces and tabs error".
    How should I write XSJS Select Query with input parameters?
    Regards,
    Rohit

    >But it gives me the "Mixed spaces and tabs error".
    Mixed spaces and tabs has nothing to do with the syntax of the statement. You used both spaces and the tab in the content - which JSLint doesn't like.  Remove the beginning spaces of each line and use only one or the other.
    The actual syntax of your statement doesn't look right.  The problem is that you are escaping the \ when you don't need to if you are using ' instead of " for your string.  You escape with \" in the first line but then escape with \' in the 2nd and 3rd line.  That is going to cause serious parsing problems with the command.

Maybe you are looking for