Pivot type query without aggregate function. Transposing

Hi experts,
Oracle 11g.
I have a table (see code example to reproduce), that has a date, a grouping, and the count of that grouping (determined in another query). I need a pivot type query, but, without the aggregate functions. This is just for a report display. I can not seem to figure this one out. Thanks for your help.
CREATE TABLE temp_task
AS
   SELECT TO_DATE ('15-NOV-2012') validation_date,
          'GROUP 1' AS group_number,
          42 AS monthly_count
     FROM DUAL
   UNION ALL
   SELECT TO_DATE ('14-DEC-2012') validation_date,
          'GROUP 1' AS group_number,
          33 AS monthly_count
     FROM DUAL
   UNION ALL
   SELECT TO_DATE ('15-NOV-2012') validation_date,
          'GROUP 2' AS group_number,
          10 AS monthly_count
     FROM DUAL
   UNION ALL
   SELECT TO_DATE ('14-DEC-2012') validation_date,
          'GROUP 2' AS group_number,
          32 AS monthly_count
     FROM DUAL
   UNION ALL
   SELECT TO_DATE ('15-NOV-2012') validation_date,
          'GROUP 3' AS group_number,
          7 AS monthly_count
     FROM DUAL
   UNION ALL
   SELECT TO_DATE ('14-DEC-2012') validation_date,
          'GROUP 3' AS group_number,
          9 AS monthly_count
     FROM DUAL;Using only SQL I need to return the following:
VALIDATION_DATE | GROUP 1 | GROUP 2 | GROUP 3
11/15/2012 | 42 | 10 | 7
12/14/2012 | 33 | 32 | 9

Hi
You always need to use an aggregate function while pivoting.
Even if you don't really need any aggregation, that is, when what you see in the table is what you'll get in the result set, you still have to use an aggregate function. If there will only be one value contrinuting to each cell, then you can use MIN or MAX. It won't matter which; since there's only 1 value, that value will be the highest of the 1, and it will also be the lowest. For NUMBER columns, you could also use SUM or AVG.
SELECT       *
FROM       temp_task
PIVOT       ( MIN (monthly_count)
         FOR group_number IN ( 'GROUP 1'
                             , 'GROUP 2'
                    , 'GROUP 3'
ORDER BY  validation_date
; Output:
VALIDATION_  'GROUP 1'  'GROUP 2'  'GROUP 3'
15-Nov-2012         42         10          7
14-Dec-2012         33         32          9It sounds like you're doing real aggregation someplace, to get monthly_count. Maybe it would be simpler and more efficient to do the pivoting at that point. What is the big picture here? Post some sample data as it is before you compute monthly_count, and the results you want from that data (if different from what you've already posted), and then let's see if we can't aggregte it and pivot it at the same time.

Similar Messages

  • Grouping result set by a column in a query without aggregate function

    In the below result set, several columns appear for one table.
    col data_Type format a12
    col column_name format a10
    set lines 100
    set pages 50
    SELECT table_name, column_name FROM user_tab_cols WHERE char_used = 'B'
    AND TABLE_name NOT LIKE 'BIN%' ORDER BY TABLE_NAME;
    TABLE_NAME                     COLUMN_NAM
    BONUS                          JOB
    BONUS                          ENAME
    DEPT                           DNAME
    DEPT                           LOC
    EMP                            JOB
    EMP                            ENAME
    EMP_DTL                        ENAME
    EMP_DTL                        LOC
    EMP_DTL                        CONVN_LOC
    MEMBER                         GENDER
    MEMBER                         TEAM
    MEMBER                         MEMBERTYPE
    MEMBER                         FIRSTNAME
    MEMBER                         LASTNAME
    MEMBER                         PHONE
    ORDERS                         STATUS
    SYS_CONFIG                     CODE_ID
    SYS_CONFIG                     FLAG_A
    TOURNAMENT                     TOURTYPE
    TOURNAMENT                     TOURNAMEI don't want the table_name to repeat for every columns within a table_name group. If i use SQLPLUS's BREAK command, it would
    suppress duplicates
    break on table_nameand the resultset would look like
    TABLE_NAME                     COLUMN_NAM
    BONUS                          JOB
                                   ENAME
    DEPT                           DNAME
                                   LOC
    EMP                            JOB
                                   ENAME
    EMP_DTL                        ENAME
                                   LOC
                                   CONVN_LOC
    MEMBER                         GENDER
                                   TEAM
                                   MEMBERTYPE
                                   FIRSTNAME
                                   LASTNAME
                                   PHONE
    ORDERS                         STATUS
    SYS_CONFIG                     CODE_ID
                                   FLAG_A
    TOURNAMENT                     TOURTYPE
                                   TOURNAME
    TYPE                           TYPE
    X                              ENAME
    Y                              ENAMEBut how can i do this using oracle SQL?

    Analytics?
    SQL> with t as
      2  (
      3  select 'A' col1, 100 col2 from dual
      4  union all
      5  select 'A' col1, 200 col2 from dual
      6  union all
      7  select 'B' col1, 800 col2 from dual
      8  union all
      9  select 'B' col1, 400 col2 from dual
    10  union all
    11  select 'C' col1, 500 col2 from dual
    12  )
    13  select decode(row_number() over (partition by col1 order by col2), 1, col1, null) col1
    14         ,col2
    15  from t
    16  /
    C      COL2
    A    100.00
         200.00
    B    400.00
         800.00
    C    500.00
    SQL>Cheers
    Sarma.

  • Trying to create a Histogram type/object for aggregate functions

    Hi,
    I am trying to create an aggregate function that will return a histogram
    type.
    It doesn't have to be an object that is returned, I don't mind returning
    a string but I would like to keep the associative array (or something
    else indexed by varchar2) as a static variable between iterations.
    I started out with the SecondMax example in
    http://www.csis.gvsu.edu/GeneralInfo/Oracle/appdev.920/a96595/dci11agg.htm#1004821
    But even seems that even a simpler aggregate function like one strCat
    below (which works) has problems because I get multiple permutations for
    every combination. The natural way to solve this would be to create an
    associative array as a static variable as part of the Histogram (see
    code below). However, apparently Oracle refuses to accept associate
    arrays in this context (PLS-00355 use of pl/sql table not allowed in
    this context).
    If there is no easy way to do the histogram quickly can we at least get
    something like strCat to work in a specific order with a "partition by
    ... order by clause"? It seems that even with "PARALLEL_ENABLE"
    commented out strCat still calls merge for function calls like:
    select hr,qtr, count(tzrwy) rwys,
    noam.strCat(cnt) rwycnt,
    noam.strCat(tzrwy) config,
    sum(cnt) cnt, min(minscore) minscore, max(maxscore) maxscore from
    ordrwys group by hr,qtr
    Not only does this create duplicate entries in the query result like
    "A,B,C" and "A,C,B" it seems that the order in rwycnt and config are not
    always the same so a user can not match the results based on their
    order.
    The difference between my functions and functions like sum and the
    secondMax demonstrated in the documentation is that secondMax does not
    care about the order in which it gets its arguments and does not need to
    maintain an ordered set in order to return the correct results. A good
    example of a built in oracle function that does care about all its
    arguments and probably has to maintain a similar data structure to the
    one I want is the PERCTILE_DISC function. If you can find the code for
    that function (or something like it) and forward a reference to me that
    in itself would be very helpful.
    Thanks,
    K.Dingle
    CREATE OR REPLACE type Histogram as object
    -- TYPE Hist10 IS TABLE OF pls_integer INDEX BY varchar2(10),
    -- retval hist10;
    -- retval number,
    retval noam.const.hist10,
    static function ODCIAggregateInitialize (sctx IN OUT Histogram)
    return number,
    member function ODCIAggregateIterate (self IN OUT Histogram,
    value IN varchar2) return number,
    member function ODCIAggregateTerminate (self IN Histogram,
    returnValue OUT varchar2,
    flags IN number) return number,
    member function ODCIAggregateMerge (self IN OUT Histogram,
    ctx2 IN Histogram) return number
    CREATE OR REPLACE type body Histogram is
    static function ODCIAggregateInitialize(sctx IN OUT Histogram) return
    number is
    begin
    sctx := const.Hist10();
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT Histogram, value IN
    varchar2)
    return number is
    begin
    if self.retval.exist(value)
    then self.retval(value):=self.retval(value)+1;
    else self.retval(value):=1;
    end if;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN Histogram,
    returnValue OUT varchar2,
    flags IN number)
    return number is
    begin
    returnValue := self.retval;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT Histogram,
    ctx2 IN Histogram) return number is
    begin
    i := ctx2.FIRST; -- get subscript of first element
    WHILE i IS NOT NULL LOOP
    if self.retval.exist(ctx2(i))
    then self.retval(i):=self.retval(i)+ctx2.retval(i);
    else self.retval(value):=ctx2.retval(i);
    end if;
    i := ctx2.NEXT(i); -- get subscript of next element
    END LOOP;
    return ODCIConst.Success;
    end;
    end;
    CREATE OR REPLACE type stringCat as object
    retval varchar2(16383), -- concat of all value to now varchar2, --
    highest value seen so far
    static function ODCIAggregateInitialize (sctx IN OUT stringCat)
    return number,
    member function ODCIAggregateIterate (self IN OUT stringCat,
    value IN varchar2) return number,
    member function ODCIAggregateTerminate (self IN stringCat,
    returnValue OUT varchar2,
    flags IN number) return number,
    member function ODCIAggregateMerge (self IN OUT stringCat,
    ctx2 IN stringCat) return number
    CREATE OR REPLACE type body stringCat is
    static function ODCIAggregateInitialize(sctx IN OUT stringCat) return
    number is
    begin
    sctx := stringCat('');
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT stringCat, value IN
    varchar2)
    return number is
    begin
    if self.retval is null
    then self.retval:=value;
    else self.retval:=self.retval || ',' || value;
    end if;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN stringCat,
    returnValue OUT varchar2,
    flags IN number)
    return number is
    begin
    returnValue := self.retval;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT stringCat,
    ctx2 IN stringCat) return number is
    begin
    self.retval := self.retval || ctx2.retval;
    return ODCIConst.Success;
    end;
    end;
    CREATE OR REPLACE FUNCTION StrCat (input varchar2) RETURN varchar2
    -- PARALLEL_ENABLE
    AGGREGATE USING StringCat;

    GraphicsConfiguration is an abstract class. You would need to subclass it. From the line of code you posted, it seems like you are going about things the wrong way. What are you trying to accomplish? Shouldn't this question be posted in the Swing or AWT forum?

  • How to create a Pivot table without aggregate function

    Dear team
    I have the following table. Follow the link to download SQL Script to create table
    https://drive.google.com/file/d/0B5nQIsvTifixV2Jkb043bVd2Zlk/view?usp=sharing
    I want to create a pivot or cross tab so that it appear like this
    LocationDesc
    >=360
    >=300
    >=270
    >=240
    <240
    Port Moresby
    John Aita
    Mawe Felix
    Augustine Eri Luke
    Joseph Aura
    Robert  ROAKEINA
    Port Moresby
    Ambane Gigmai
    Paul Dem
    Henry  Wanpis
    Tiniki Bau
    William Laki NIGINTS
    Port Moresby
    June Vutnamur
    Alphonse Waieng
    Rex TOMARA
    Mika OROMOIA
    Eveni Ekeni
    Mount Hagen
    Dominic Kouroi
    Senis Ospea
    JOSEPH KLAWA
    Peter WAI
    PHILIP JAMES
    Lae 
    Henry TIAS
    Mathew Dominic
    Jobert Idigel
    Wagi Jerry
    Christopher Bianta
    etc
    etc
    etc
    etc
    etc
    etc
    Marsh Narewec

    Hi Marsh,
    To achieve your requirement, you may reference the below query.
    --pivot the table to get the expected output
    ;WITH cte AS(
    SELECT *,ROW_NUMBER() OVER(PARTITION BY LocationDesc,BandGroup ORDER BY BandGroup) AS rn FROM [TmpBandGroup]
    SELECT LocationDesc,[>=360],[>=300],[>=270],[>=240],[<240]
    FROM cte
    PIVOT
    (MAX(EmployeeName) FOR BandGroup IN([>=360],[>=300],[>=270],[>=240],[<240])) PVT
    ORDER BY LOCATIONDESC
    --the pivot result can be validated with the queries below
    ;WITH cte AS(
    SELECT *,ROW_NUMBER() OVER(PARTITION BY LocationDesc,BandGroup ORDER BY BandGroup) AS rn FROM [TmpBandGroup]
    ,cte2 AS
    SELECT RN, LocationDesc,[>=360],[>=300],[>=270],[>=240],[<240]
    FROM cte
    PIVOT
    (MAX(EmployeeName) FOR BandGroup IN([>=360],[>=300],[>=270],[>=240],[<240])) PVT
    SELECT LocationDesc, COUNT([>=360]) [>=360] ,COUNT([>=300]) [>=300],COUNT([>=270]) [>=270],COUNT([>=240]) [>=240],COUNT([<240]) [<240]
    FROM cte2
    group by LocationDesc
    ORDER BY LocationDesc
    SELECT LocationDesc,bandgroup,COUNT(EmployeeName) FROM [TmpBandGroup] group by LocationDesc ,bandgroup
    ORDER BY LocationDesc,bandgroup DESC
    If you have any feedback on our support, you can click
    here.
    Eric Zhang
    TechNet Community Support

  • Update of a table from a select query with aggregate functions.

    Hello All,
    I have problem here:
    I have 2 tables A(a1, a2, a3, a4, a4....... ) and B( a1, a2, b1, b2, b3). I need to calculate the avg(a4-a3), Max(a4-a3) and Min(a4-a3) and insert it into table B. If the foreign keys a1, a2 already exist in table B, I need to do an update of the computed values into column b1, b2 and b3 respectively, for a1, a2.
    Q1. Is it possible to do this with a single query ? I would prefer not to join A with B because the table A is very large. Also columns b1, b2 and b3 are non-nullable.
    Q2. Also if a4 and a3 are timestamps what is the best way to find the average? A difference of timestamps yields INTERVAL DAY TO SECOND over which the avg function doesn't seem to work. The averages, max and min in my case would be less than a day and hence all I need is to get the data in the hh:mm:ss format.
    As of now I'm using :
    TO_CHAR(TO_DATE(ABS(MOD(TRUNC(AVG(extract(hour FROM (last_modified_date - created_date))*3600 +
    extract( minute FROM (last_modified_date - created_date))*60 +
    extract( second FROM (last_modified_date - created_date)))
    ),86400)),'sssss'),'hh24":"mi":"ss') AS avg_time,
    But this is very long drawn. Something more compact and efficient would be nice.
    Thanks in advance for your inputs.
    Edited by: 847764 on Mar 27, 2011 5:35 PM

    847764 wrote:
    Hi,
    Thanks everyone for such fast replies. Malakshinov's example worked fine for me as far as updating the table goes. As for the timestamp computations, I'm posting additional info: Sorry, I don't understand.
    If Malakshinov's example worked for updating the table, but you still have problems, does that mean you have to do something else besides update the table? If so, what?
    Oracle version : Oracle Database 11g Enterprise Edition Release 11.2.0.1.0
    Here are the table details :
    DESC Table A
    Name Null Type
    ID               NOT NULL NUMBER
    A1               NOT NULL VARCHAR2(4)
    A2               NOT NULL VARCHAR2(40)
    A3               NOT NULL VARCHAR2(40)
    CREATED_DATE NOT NULL TIMESTAMP(6)
    LAST_MODIFIED_DATE TIMESTAMP(6) DESCribing the tables can help clarify some things, but it's no substitute for posting CREATE TABLE and INSERT statements. With only a description of the table, nobody can re-create the problem or test their ideas. Please post CREATE TABLE and INSERT statements for both tables as they exist before the MERGE. If table b doen't contain any rows before the MERGE, then just say so, but you still need to post a CREATE TABLE statement for both tables, and INSERT statements for table a.
    The objective is to compute the response times : avg (LAST_MODIFIED_DATE - CREATED_DATE), max (LAST_MODIFIED_DATE - CREATED_DATE) and min (LAST_MODIFIED_DATE - CREATED_DATE) grouped by A1 and A2 and store it in table B under AVG_T, MAX_T and MIN_T. Since AVG_T, MAX_T and MIN_T are only used for reporting purposes we have kept it as Varchar (though I think keeping it as timestamp would make more sense). I think a NUMBER would make more sense (the number of minutes, for example), or perhaps an INTERVAL DAY TO SECOND. If you stored a NUMBER, it would be easy to compute averages.
    In table B the times are stored in the format : hh:mm:ss. We don't need milliseconds precision. If you don;'t need milliseconds, then you should use DATE instead of TIMESTAMP. The functions for manipulating DATEs are much better.
    Hence I was calculating is as follows:
    -- Avg Time
    TO_CHAR(TO_DATE(ABS(MOD(TRUNC(AVG(extract(hour FROM (last_modified_date - created_date))*3600 +
    extract( minute FROM (last_modified_date - created_date))*60 +
    extract( second FROM (last_modified_date - created_date)))
    ),86400)),'sssss'),'hh24":"mi":"ss') AS avg_time,
    --Max Time
    extract (hour FROM MAX(last_modified_date - created_date))||':'||extract (minute FROM MAX(last_modified_date - created_date))||':'||TRUNC(extract (second FROM MAX(last_modified_date - created_date))) AS max_time,
    --Min Time
    extract (hour FROM MIN(last_modified_date - created_date))||':'||extract (minute FROM MIN(last_modified_date - created_date))||':'||TRUNC(extract (second FROM MIN(last_modified_date - created_date))) AS min_timeIs this something that has to be done before or after the MERGE?
    Post the complete statement.
    Is this part of a query? Where's the SELECT keyword?
    Is this part of a DML operation? Where's the INSERT, or UPDATE, or MERGE keyword?
    What are the exact results you want from this? Explain how you get those results.
    Is the code above getting the right results? Are you just asking if there's a better way to get the same results?
    You have to explain things very carefully. None of the people who want to help you are familiar with your application, or your needs.
    I just noticed that my reply is horribly formatted - apologies! I'm just getting the hang of it.Whenever you post formatted text (such as query 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to write SQL query and apply aggregate functions on it

    Hello experts,
    Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
    Thanks a lot in advance

    HI Mr. Cool
    you can see the below code for using aggregate functions.
    where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
    DATA: TOTAL_ENTRIES TYPE I,
          TOTAL_ATT TYPE I,
          MAX_ATT TYPE I,
          AVG_ATT TYPE I.
    SELECT COUNT( DISTINCT ARTIST )
           SUM( SEATSOCCU )
           MAX( SEATSOCCU )
           AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
    MAX_ATT, AVG_ATT).
    Thanks
    Lalit Gupta

  • Using Aggregate function in queries

    Hi all,
              Please take a look on this query and suggest me why i'm getting the error..
    This is my simple query using aggregate function in it..
    SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY)
    FROM TABLE1 T1, TABLE2 T2
    WHERE T1.ID=T2.ID
    GROUP BY T1.NAME, T1.DESCRIPTION
    Above query added with a sub-query in the select segment..
    SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY), (SELECT AVG(T3.PRICE) FROM TABLE1 TT1, TABLE3 T3 WHERE TT1.ID=T3.ID AND TT1.ID=T1.ID) AV_PRICE
    FROM TABLE1 T1, TABLE2 T2
    WHERE T1.ID=T2.ID
    GROUP BY T1.NAME, T1.DESCRIPTION
    When i add a sub-query which has aggregate function in it, i'm getting the 'ORA-00979: not a GROUP BY expression' error.

    What is your DB Version. Your query works without any issue in my DB. I used WITH clause to create the sample data. The query highlighted in BLUE is the actual query.
    SQL> select * from v$version where rownum = 1;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    SQL> with table1
      2  as
      3  (
      4    select 1 id, 'karthick' name, 'user name' description from dual
      5  ),
      6  table2
      7  as
      8  (
      9    select 1 id, 100 quantity from dual
    10  ),
    11  table3
    12  as
    13  (
    14    select 1 id, 10 price from dual
    15  )
    16  select t1.name
    17       , t1.description
    18       , sum(t2.quantity)
    19       , (
    20           select avg(t3.price)
    21             from table1 tt1
    22                , table3 t3
    23            where tt1.id = t3.id
    24              and tt1.id = t1.id
    25         ) av_price
    26    from table1 t1
    27       , table2 t2
    28   where t1.id = t2.id
    29   group
    30      by t1.name
    31       , t1.description;
    NAME     DESCRIPTI SUM(T2.QUANTITY)   AV_PRICE
    karthick user name              100         10
    SQL>

  • Why doesn't PIVOT clause work with COLLECT aggregate function in 11g ?

    Hello all !
    I am really puzzled as to what is considered an aggregate function in the context of the PIVOT clause in 11g.
    I have been toying with quite a few things related to collections lately and this arose as an aside :
    CREATE TABLE TEST_COLL
       NODE_ID    VARCHAR2(15 CHAR) NOT NULL,
       NODE_VALUE VARCHAR2(45 CHAR) NOT NULL,
       NODE_LEVEL NUMBER(1)         NOT NULL
    CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
       NODE_KEY  VARCHAR2( 15 CHAR),
       NODE_NAME VARCHAR2(127 CHAR)
    CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL;At this stage I am sure we all agree that the query
    SELECT NODE_LEVEL,
           CAST(COLLECT(TREE_NODE(NODE_ID, NODE_VALUE)) AS TREE_NODES) AS NODES
      FROM TEST_COLL
    GROUP BY NODE_LEVEL;is perfectly valid as the COLLECT function is an aggregate function according to the [Official Documentation|http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions031.htm#i1271564]
    But then, one of the following two queries should work
    SELECT CAST(REGION_NODES     AS TREE_NODES) AS REGIONS,
           CAST(DEPARTMENT_NODES AS TREE_NODES) AS DEPARTMENTS,
           CAST(AREA_NODES       AS TREE_NODES) AS AREAS,
           CAST(CENTRE_NODES     AS TREE_NODES) AS CENTRES
      FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM TREE_COLL
    PIVOT (COLLECT(NODE) FOR NODE_LEVEL IN (1 AS REGION_NODES,
                                             2 AS DEPARTMENT_NODES,
                                             3 AS AREA_NODES,
                                             4 AS CENTRE_NODES
    or (better)
    SELECT REGION_NODES     AS REGIONS,
           DEPARTMENT_NODES AS DEPARTMENTS,
           AREA_NODES       AS AREAS,
           CENTRE_NODES     AS CENTRES
      FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM TREE_COLL
    PIVOT (CAST(COLLECT(NODE) AS TREE_NODES) FOR NODE_LEVEL IN (1 AS REGION_NODES,
                                                                 2 AS DEPARTMENT_NODES,
                                                                 3 AS AREA_NODES,
                                                                 4 AS CENTRE_NODES
           );yet, both fail with
    ORA-56902: expect aggregate function inside pivot operationInvestigating further, I found the same behaviour when using XMLAGG as the aggregate function in the PIVOT clause.
    Is this normal ? And if it is, is there any other way to achieve the result I was anticipating ?
    My version is
    SQL> SELECT BANNER FROM V$VERSION;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for 64-bit Windows: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - ProductionThanks in advance
    Best Regards
    Philip

    Most likely a bug. But you can bypass it by using any other aggregate making sure group consists of a single row and apply collect to a pivoted value. Yes, the cost is double aggregation. And also there is another cost - you would need to create MAP member function otherwise aggreations like MAX/MIN, etc. will not work:
    CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
       NODE_KEY  VARCHAR2( 15 CHAR),
       NODE_NAME VARCHAR2(127 CHAR),
       map member function f return varchar2
    Type created.
    CREATE OR REPLACE TYPE BODY TREE_NODE AS
      map member function f return varchar2 is
      begin
         return NODE_NAME;
      end f;
    end;
    Type body created.
    CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL
    Type created.
    SQL> select  *
      2    from  test_coll
      3  /
    NODE_ID NODE_VALUE NODE_LEVEL
    1       A                   1
    2       B                   2
    3       C                   3
    4       D                   4
    5       E                   1
    6       F                   2
    7       G                   3
    8       H                   4
    8 rows selected.
    SQL> Now:
    SELECT CAST(COLLECT(REGION_NODES)     AS TREE_NODES) AS REGIONS,
           CAST(COLLECT(DEPARTMENT_NODES) AS TREE_NODES) AS DEPARTMENTS,
           CAST(COLLECT(AREA_NODES)       AS TREE_NODES) AS AREAS,
           CAST(COLLECT(CENTRE_NODES)     AS TREE_NODES) AS CENTRES
      FROM (
            SELECT  ROWID RID,
                    NODE_LEVEL,
                    TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM  TEST_COLL
    PIVOT (MAX(NODE) FOR NODE_LEVEL IN (
                                         1 AS REGION_NODES,
                                         2 AS DEPARTMENT_NODES,
                                         3 AS AREA_NODES,
                                         4 AS CENTRE_NODES
    REGIONS(NODE_KEY, NODE_NAME)                         DEPARTMENTS(NODE_KEY, NODE_NAME)                     AREAS(NODE_KEY, NODE_NAME)                           CENTRES(NODE_KEY, NODE_NAME)
    TREE_NODES(TREE_NODE('1', 'A'), TREE_NODE('5', 'E')) TREE_NODES(TREE_NODE('6', 'F'), TREE_NODE('2', 'B')) TREE_NODES(TREE_NODE('7', 'G'), TREE_NODE('3', 'C')) TREE_NODES(TREE_NODE('8', 'H'), TREE_NODE('4', 'D'))
    SQL> SY.

  • Aggregate function in the query

    Hi gurus,
    What makes presentation layer send queries with Aggregate( by ) function eventhough this function is not used in the column formulas?
    Now comes a long explanation - only for the patient ones :-)
    I am working OBIEE / Essbase.
    A strange thing happened to one of my reports - exactly the same report (pivot) in production (old repository) works fine, but brings wrong results on the new repository.
    I found out that SQL sent to OBIEE is different.
    With old repository, it sends a query with 'Aggregate ( by)' function used for measures. However with the new one, it sends just column names without the Aggregate.
    Where shall I look for the difference?
    -- OLD (Good) query -----------
    SELECT DIM_BATCH_HEADERS."Gen3,DIM_BATCH_HEADERS" saw_0,
    PROD_QTY.PROD_ACTUAL_QTY_KG/1000 saw_1,
    DIM_COMPONENT."Gen3,DIM_COMPONENT" saw_2, ' ' saw_3,
    COST.COMP_ACTUAL_COST_ILS_PER_TON saw_4, 0 saw_5,
    COST.ACTUAL_COST_K_ILS saw_6, 0 saw_7,
    AGGREGATE(saw_1 BY ),
    AGGREGATE(saw_4 BY ),
    AGGREGATE(saw_6 BY ),
    AGGREGATE(saw_1 BY saw_0, saw_5),
    AGGREGATE(saw_4 BY saw_0, saw_5),
    AGGREGATE(saw_6 BY saw_0, saw_5)
    FROM "COP_MAAD#1" WHERE (COMP_QTY.COMP_RELEVANT > 0)
    AND (DIM_TIME."YEAR" = '2009')
    AND (DIM_BATCH_HEADERS."Gen2,DIM_BATCH_HEADERS" = 'ABC')
    ORDER BY saw_1 DESC, saw_4 DESC, saw_0, saw_2, saw_3, saw_5, saw_7
    -- NEW (Incorrect) Query ---------------
    SELECT DIM_BATCH_HEADERS."Gen3,DIM_BATCH_HEADERS" saw_0,
    PROD_QTY.PROD_ACTUAL_QTY_KG/1000 saw_1,
    DIM_COMPONENT."Gen3,DIM_COMPONENT" saw_2,
    ' ' saw_3, COST.COMP_ACTUAL_COST_ILS_PER_TON saw_4,
    0 saw_5,
    COST.ACTUAL_COST_K_ILS saw_6,
    0 saw_7 FROM "COP_MAAD#1"
    WHERE (COMP_QTY.COMP_RELEVANT > 0) AND (DIM_TIME."YEAR" = '2009')
    AND (DIM_BATCH_HEADERS."Gen2,DIM_BATCH_HEADERS" = 'ABC') ORDER BY saw_1 DESC, saw_4 DESC
    Thanks,
    Alex

    Hi,
    Can anybody reply to the above question please?
    regards,
    Siva

  • Issue in pivot while using aggregate functions

    when I use this below query in oracle sql developer
    ------------->select sum(round(8.08/0.54,2)*30) from dual.
    i am getting result as 448.8.it is a correct value
    but i use this below queries in pivot as same like above query i am getting result of doubled value 914.4.
    PIVOT
    SUM(round(ROUND(sellout,2)/6,2)) AS LAST_6_MON_SELL_OUT,
    SUM(ROUND(inventory,2)) AS INVENTORY_INTINS_1,
    Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)*30) As Stockperday
    FOR PRODUCT IN (56,78)
    actually i am getting value for SUM(round(ROUND(sellout,2)/6,2)) is 0.54,*SUM(ROUND(inventory,2))* is 8.08 i the above query ,but i am getting wrong value for this aggregate function Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)30)* as 914.4.but actual value is 448.8
    why this problem.can anybody explain me.why this problem

    Try ur luck in 'sql plsql thread'
    PL/SQL

  • Aggregate function in native query (EJB 3.0)

    How do you run a aggregate function in a native query? I have a particular use case, for reporting purposes, where the result set is too large to fetch the actual CMP collection, thus I need to execute a native count/avg select. I want some thing like,
    Integer totalRecords = (Integer)
           em.createNativeQuery("select count(*) from records").getSingleResult();

    Oracle is intelligent enough to use index only if query result filtering is based on it and result set is less than 5% of the total data set.Sorry to be blunt but that 5% stuff is nonsense.
    Here since the index column is not used in the WHERE clause, oracle performs full table scan.That's not true either. Under the right circumstances the optimizer can use the index, even without a WHERE clause in the query:
    SQL> create table t as select * from dba_objects where object_type is not null;
    Table created.
    SQL> alter table t modify object_type not null;
    Table altered.
    SQL> create index t_idx on t(object_type);
    Index created.
    SQL> explain plan for
      2  select object_type, count(*) from t group by object_type;
    Explained.
    | Id  | Operation             | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT      |       |    44 |   396 |    60   (7)| 00:00:01 |
    |   1 |  HASH GROUP BY        |       |    44 |   396 |    60   (7)| 00:00:01 |
    |   2 |   INDEX FAST FULL SCAN| T_IDX | 72474 |   636K|    57   (2)| 00:00:01 |
    -------------------------------------------------------------------------------With the OP's query, it (apparently) can not be satisfied by using only the index.
    WHERE TO_CHAR(COL) = TO_CHAR(COL)I don't even know what this means. Usually if you perform a function on an indexed column, the optimizer will not use the index (unless of course it's an fbi).

  • Rounding the aggregate function in a pivot table

    How do I round the avg(GRADE) when I tried just wrapping it around the avg function I get an error message saying expect aggregate function inside pivot operation
    pivot
    ( avg(GRADE)
    for Column
    in ('1012222','2221112','333113' );
    Thanks for the help.
    Edit : Sorry wasn't very clear all thats shown is the pivot part of the statement.
    Edited by: 836321 on Feb 13, 2011 8:56 AM
    Edited by: 836321 on Feb 13, 2011 8:58 AM

    Hi, and welcome to the forum.
    It is hard to see how your piece of pseudo SQL is related to your subject title.
    There should not be any problem in wrapping ROUND around AVG:
    SQL> select deptno, round(avg(sal)) from emp
    where deptno in (10,20)
    group by deptno
        DEPTNO ROUND(AVG(SAL))
            20            2175
            10            2917
    2 rows selected.Edit: Sorry, did not recognize you query bit. You probably are asking about this:
    SELECT * FROM
       (SELECT deptno, sal FROM emp)
        PIVOT
       (ROUND(AVG(sal)) FOR deptno IN (10 AS Accounting, 30 AS Sales));
    Error at line 4
    ORA-56902: expect aggregate function inside pivot operationSuppose you have to (There might be other ways)
    SQL> SELECT Round(accounting), round(sales) FROM
       (SELECT deptno, sal FROM emp)
        PIVOT
       (AVG(sal) FOR deptno IN (10 AS Accounting, 30 AS Sales));
    ROUND(ACCOUNTING) ROUND(SALES)
                 2917         1567
    1 row selected.Regards
    Peter
    Edited by: Peter on Feb 13, 2011 9:05 AM
    Edited by: Peter Gjelstrup on Feb 13, 2011 9:08 AM

  • Pivot table wihtout Aggregate Functions ( Urgent Please. )

    I am trying to select date and time. But having a hard time since I dont have any aggregate function that is needed. Just pivot the rows to columns.
    IN sql 
    stage
    starttime
    endtime
    1
    1/22/2011 15:31
    1/22/2011 15:32
    2
    1/22/2011 15:33
    1/22/2011 15:34
    3
    1/22/2011 15:35
    1/22/2011 15:36
    Required 
    starttime_s1
    endtime_s1
    starttime__s2
    endtime_s2
    starttime_s3
    endtime_s3
    1/22/2011 15:31
    1/22/2011 15:32
    1/22/2011 15:33
    1/22/2011 15:34
    1/22/2011 15:35
    1/22/2011 15:36

    What is it that you're trying to accomplish with this?
    The reason I ask is that pivoting data is a display function and therefore best left to the application or reporting tier.
    If you're going to insist on "driving screws with a hammer" and really want to do this in SQL, the next question is, Is there a set number of "Stages" that will exist? Is it always going to be 3 stages and only 3 stages?
    If the answer is YES, there will be a fixed number of stages, then it's a simple thing to do with either a PIVOT or CASE statements. (my personal preference is to use case statements, especially if you're pivoting 2 or more columns)
    If the answer is NO, the number is stages can vary... You're left with a Dynamic PIVOT. Dynamic Pivots are a bit more complex to write but there is enough sample code out on the interwebs that you won't have a problem finding the correct syntax. 
    The real problem with a Dynamic Pivot query is the fact that it's pretty much useless. You can't do much (if anything at all) with it... Due to the fact that they have variable numbers of columns, they can't be used in views or procs and I can't think of
    a singe, off the shelf, reporting platform that will allow accommodate data source that has a different number of columns every time it executes... So unless you're going to be content looking at the results in SSMS or developing a custom application, I don't
    see the point.
    Also... Aggregates aren't a problem based on the data you're showing. You only have 1 start time and 1 end time per stage. Using either the MIN or MAX aggregate functions will work to give you the desired result.
    Anyway, hope that helps,
    Jason
    Jason Long

  • Aggregate function on "large value type"

    We are constrained to use a model that stores records in a main table and various attributes of the record in a second table. Something like this: main record table CAR, attribute table CAR_DETAILS with CAR_DETAILS have key value pairs like "color"
    "blue" and "doors" "4".
    For reports we need to flatten the one to many nature of this to get CAR and color and doors by using an aggregate function like: 
    car_id, max(car_detail.value) filtered on car_detail.key = "color", max(car_detail.value) filtered on car_detail.key = "doors". 
    This works on other tables but the car_detail table (shall we say) appears to store its values as blobs. In any case when we attempt to aggregate we get "The query uses an aggregate function on a large value type expression. Large value type expressions
    can not be aggregated."
    Since we can't change the model, we would need to use another function to change this to a smaller string (or date, these are actually mostly date), but none of the very limited set of functions available seems to work to make this aggregation possible (and
    there is no "first" or anything else similar). 
    The list of functions available in Report Model Queries can be found at https://msdn.microsoft.com/en-us/library/ee210538.aspx
    Appreciate any ideas on how to solve this
     

    I found a work around : create a second dataset reversing the direction:
    car_detail.key, car_detail.value, car_id
    with this filtered by car_detail.key = "color" (or doors etc)
    Then use a lookup from the first dataset to the second to display the data:
    =Lookup(Fields!car_Id.Value,Fields!Icar_Id.Value,Fields!car_detail.Value, "DataSet2")
    where the 1st field is in the main report dataset, the second and third are in the lookup dataset, and the 4th parameter is the name of the lookup dataset. 
    Would still really like to have a solution that allows aggregation for ease of use and efficiency. 

  • Error in using aggregate function in Outer Query in Siebel Analytics

    Hi,
    When I am using aggregate function in outer query in Siebel Analytics I am facing error.
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 59111] The SQL statement must include a GROUP BY clause. (HY000)
    Bellow is the code.
    SELECT test1.username saw_0, test1.desg saw_1,COUNT (test2.querydate) saw_2
    FROM (SELECT POSITION.CBL username,
    POSITION.CBP desg
    FROM "CM"
    WHERE (POSITION.BPTCD = 'Marketing')
    AND (POSITION.EDate =TIMESTAMP '1899-01-01 00:00:00'
    ) test1,
    (SELECT users.UN username,
    measures."Query Count" querycount,
    measures."Max Total Time" secs,
    topic.db dashboardname,
    "Query Time".DATE querydate
    FROM "Plan"
    WHERE (topic."Dashboard Name" IN ('DS'))) test2
    WHERE test2.username = LOWER (test1.username)
    AND test2.dashboardname = 'DS'
    GROUP BY test1.username, test1.desg

    Should your query be a valid SQL query?
    I can't think that the query you have would be valid in a SQL plus window.
    Chris

Maybe you are looking for

  • T520 upgrade hard drive and memory

    I just read a similar thread, but it's a year old and I'd like to see the current recommendations. Here is my configuration: Screen Size 15.6 inches Screen Resolution 1366 x 768 Processor 2.5 GHz Core i5-2520M RAM 8 GB DDR3-SDRAM Memory Speed 1333 MH

  • Unable to activate adobe photoshop cs5.1 subscription edition.  Product activation is required.

    I installed adobe photoshop cs5.1 and so far the installation worked.  Entering my key and running photoshop for the first time worked.  Upon closing photoshop and reopening photoshop, it asks for internet access again and says it needs to be activat

  • Updating work hours

    Greetings everyone, I'm trying to update a field in a table with the total work hours in a specific month. To achieve this I've tried using a piece of SQL found in several other threads to retrieve the number of work days in a month. This doesn't wor

  • Modify attribute value

    Here is a part of an XML file: <caseManagement>                <investigationNote noteSeqNo="1" noteNo="1" investigationNoteType="INN" investigationDesc="5oy6B3eHj%2FE%3D"/>                <investigationNote noteSeqNo="2" noteNo="2" investigationNote

  • Difference function

    Hi, Is there any equivalent for SQL Server's difference function in Oracle. If not, is it possible to achieve the same ? Thanks, Sam