Request help with query group by

Hi,
I have the following table structure with values
CREATE TABLE DUMMY
    SR_NUMBER          VARCHAR2(100 CHAR),
    ASSIGNMENT_GROUP   VARCHAR2(100 CHAR),
    REASSIGNMENT_COUNT VARCHAR2(100 CHAR),
    CREATED DATE,
    CLOSED DATE,
    TARGET_DATE DATE
insert into dummy values('AAA','A','1','02-OCT-11','25-OCT-11','09-OCT-11');
insert into dummy values('ABC','A','1','03-SEP-12','26-SEP-11','10-SEP-11');
insert into dummy values('AVB','A','1','02-NOV-13','25-NOV-13','09-NOV-13');
insert into dummy values('AFT','B','1','02-OCT-11','25-OCT-11','09-OCT-11');
insert into dummy values('ACS','B','1','02-JAN-12','25-JAN-12','09-JAN-12');
insert into dummy values('AVC','B','1','02-OCT-13','25-OCT-13','09-OCT-13');
insert into dummy values('AAD','B','1','02-MAR-14','25-MAR-14','09-MAR-14');
insert into dummy values('AAA','C','1','02-OCT-11','25-OCT-11','09-OCT-11');
insert into dummy values('AAA','D','1','02-JUN-11','25-JUN-11','09-JUN-11');
insert into dummy values('AAA','E','1','02-APR-12','25-APR-12','09-APR-12');
insert into dummy values('AAA','A','1','02-FEB-13','25-FEB-13','09-FEB-13');
?I have the following requirement, the output should be:
Ticket count (sr_number)
% of tickets inside DL
Number of tickets inside DL
Average cycle time (cycle time = closed date - created date)
Total cycle time (cycle time = closed date - created date)
Number of reassignments (sum)
DL - (deadline) formula is, closed date <= target_date
This should be displayed, grouped by year, then month and then by assignment group. The values should be in descending order(dates) Not sure how group by will work here.
I am able to write the basic code for the above, but group by based on year, month and assignment group is pretty confusing to me.
Can someone provide me a good code...

This may not give you exactly what you want, but hopefully, it will give you something to work with:
WITH tickets AS (
  SELECT TO_CHAR(created, 'YYYY') created_year,
         TO_CHAR(created, 'MM') created_month,
         assignment_group,
         COUNT(sr_number) ticket_count,
         AVG(closed - created) avg_cycle_time,
         SUM(closed - created) tot_cycle_time,
         COUNT(reassignment_count) reassign_count
   FROM dummy
   GROUP BY TO_CHAR(created, 'YYYY'),
            TO_CHAR(created, 'MM'),
            assignment_group
dl_tickets AS (
  SELECT TO_CHAR(created, 'YYYY') created_year,
         TO_CHAR(created, 'MM') created_month,
         assignment_group,
         COUNT(sr_number) ticket_in_dl_count
    FROM dummy
    WHERE closed <= target_date
    GROUP BY TO_CHAR(created, 'YYYY'),
          TO_CHAR(created, 'MM'),
          assignment_group
SELECT t.created_year,
       t.created_month,
       t.assignment_group,
       t.ticket_count,
       NVL(dl.ticket_in_dl_count, 0) ticket_in_dl_count,
       NVL(dl.ticket_in_dl_count/t.ticket_count, 0) * 100 pct_ticket_in_dl_count,
       t.avg_cycle_time,
       t.tot_cycle_time,
       t.reassign_count
  FROM tickets t,
       dl_tickets dl
  WHERE t.created_year = dl.created_year (+)
  AND t.created_month = dl.created_month (+)
  ORDER BY created_year DESC, created_month DESCEdited by: user1983440 on May 27, 2013 3:47 PM - Added reassign_count
Edited by: user1983440 on May 27, 2013 3:54 PM - Added ORDER BY

Similar Messages

  • Requesting help with query

    Well the idiots that designed this database table that I'm working with decided to store dates in a NUMBER(8) field in the format of YYYYMMWW -- that's the year+month+week of year.
    If I have records such as:
    PERIOD     EMPID     REVENUE
    20070626     11122     396080.77
    20070727     11122     399667.83
    20070728     11122     409765.94
    20070729     11122     430246.10
    20070730     11122     437611.86
    20070831     11122     463508.75
    20070832     11122     468487.00
    How can I get a query result to look as this:
    PERIOD     EMPID     REVENUE
    20070626     11122     396080.77
    20070730     11122     437611.86
    20070832     11122     468487.00
    The output should only have the last record from each month.

    Maybe something like:
    SQL> WITH test_tab AS
      2       (SELECT 20070626 period, 11122 empid, 396080.77 revenue
      3          FROM DUAL
      4        UNION ALL
      5        SELECT 20070727, 11122, 399667.83
      6          FROM DUAL
      7        UNION ALL
      8        SELECT 20070728, 11122, 409765.94
      9          FROM DUAL
    10        UNION ALL
    11        SELECT 20070729, 11122, 430246.10
    12          FROM DUAL
    13        UNION ALL
    14        SELECT 20070730, 11122, 437611.86
    15          FROM DUAL
    16        UNION ALL
    17        SELECT 20070831, 11122, 463508.75
    18          FROM DUAL
    19        UNION ALL
    20        SELECT 20070832, 11122, 468487.00
    21          FROM DUAL)
    22  SELECT period, empid, revenue
    23    FROM (SELECT period,
    24                 ROW_NUMBER () OVER (PARTITION BY TO_NUMBER
    25                                                    (SUBSTR (TO_CHAR (period),
    26                                                             5,
    27                                                             2
    28                                                            )
    29                                                    ) ORDER BY TO_NUMBER
    30                                                       (SUBSTR (TO_CHAR (period),
    31                                                                7
    32                                                               )
    33                                                       ) DESC) rn,
    34                 empid, revenue
    35            FROM test_tab)
    36   WHERE rn = 1
    37  /
        PERIOD      EMPID    REVENUE
      20070626      11122  396080.77
      20070730      11122  437611.86
      20070832      11122     468487
    3 rows selected.
    SQL> Regards,
    Jo

  • Help with a group query

    I have the following table
    EX_ID
    EX_NAME
    EX_SURNAME
    EX_FLAG
    1
    TOM
    JONES
    Y
    1
    JIM
    SLIM
    N
    1
    BO
    SELECTA
    Y
    2
    AIRES
    BEARS
    N
    2
    JIM
    DAVIES
    Y
    3
    PAUL
    BALL
    N
    3
    YOU
    KNOW
    N
    I need to create a query that only displays one of the ex_id’s, it doesn’t matter which one.  When the query has been run it will look like below:
    EX_ID
    EX_NAME
    EX_SURNAME
    EX_FLAG
    1
    TOM
    JONES
    Y
    2
    AIRES
    BEARS
    N
    3
    YOU
    KNOW
    N
    Can anyone help with this query?

    SELECT * FROM
    SELECT *,ROW_NUMBER () OVER (PARTITION BY ex_id ORDER BY (SELECT 0))
    FROM tbl
    ) AS Der WHERE rn=1
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • Request Help With Oracle BI Apps 7.9.x development license

    Request some one from Oracle to PLEASE help with the following query or help me to move the post to right forum.
    I have downloaded BI Apps 7.9 to load it on top of BI EE. These are received from Development Downloads under OTN site (not eDelivery). Both these are planned as development install on one machine with sufficient specs on Windows 32 bit platform.
    BI EE is loaded and starts successfully. Then switched of the services and started to load BI Apps CD1. Done it successfully. Next while starting to install Informatica PowerCenter 7.1.4 it asks product license key. Please help to know where to get this key? Also please help with any connectivity and options key, as well as those for any other products, related to this objective.
    Many thanks,

    Hi RAJC,
    Many thanks for the suggestion. I have moved past that aspect now with this help. Have also verified that everything is working well with BI server, presentation services, scheduler server etc. Admin tool works fine.
    But have difficulty connecting DAC client to the database. The login window does not bring up option to select suitable driver for connecting to Oracle Database 10.2.0.x Also, wonder what table owner name and pw will work here? are they the same as those for schema owner? that is sh.rpd etc? The BI apps version is 7.9 and BIEE is 10.1.3.3
    Thanks

  • Help with query calculations (recursive)

    Hi All,
    I want some help with a query using a base rate and the result use in the next calculation year.
    Here an example:
    create table rate_type(
    rate_type_id    number,
    rate_desc       nvarchar2(50),
    rate_base_year  number
    insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (1, 'Desc1', 4.6590);
    insert into rate_type(rate_type_id, rate_desc, rate_base_year) values (2, 'Desc2', 4.6590);
    create table rates (
    rate_type_id number
    rate_year    number,
    rate_value   number
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2012, 1.2);
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2013, 1.3);
    insert into rates(rate_type_id, rate_year, rate_value) values (1, 2014, 1.4);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2012, 1.2);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2013, 1.3);
    insert into rates(rate_type_id, rate_year, rate_value) values (2, 2014, 1.4);The calculation for the first year should be the base rate of the rate type. The next year should use the result of the previous year and so on.
    The result of my sample data is:
    2012 = 4.659 + 1.2 + 4.659 * (1.2 * 0.01) = 5.9149
    2013 = 5.9149 + 1.3 + 5.9149 * (1.3 * 0.01) = 7.1859
    2014 = 7.1859 + 1.4 + 7.1859 * (1.4 * 0.01) = 8.4721Query result:
    NAME 2012 2013 2014
    Desc1 5.9149 7.1859 8.4721
    Desc2 XXXX XXX XXXX
    How can I do this in one select statement? Any ideas?
    Thanks!

    Assuming you are on 11.2:
    with t as (
               select  a.rate_type_id,
                       rate_desc,
                       rate_year,
                       rate_base_year,
                       rate_value,
                       count(*) over(partition by a.rate_type_id) cnt,
                       row_number() over(partition by a.rate_type_id order by rate_year) rn
                 from  rate_type a,
                       rates b
                 where a.rate_type_id = b.rate_type_id
        r(
          rate_type_id,
          rate_desc,
          rate_year,
          rate_base_year,
          rate_value,
          cnt,
          rn,
          result
         ) as (
                select  rate_type_id,
                        rate_desc,
                        rate_year,
                        rate_base_year,
                        rate_value,
                        cnt,
                        rn,
                        rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
                  from  t
                  where rn = 1
               union all
                select  t.rate_type_id,
                        t.rate_desc,
                        t.rate_year,
                        t.rate_base_year,
                        t.rate_value,
                        t.cnt,
                        t.rn,
                        r.result + t.rate_value + r.result * t.rate_value * 0.01 result
                  from  r,
                        t
                  where t.rate_type_id = r.rate_type_id
                    and t.rn = r.rn + 1
    select  *
      from  (
             select  rate_desc name,
                     rate_year,
                     result
               from  r
               where rn <= cnt
      pivot (sum(result) for rate_year in (2012,2013,2014))
      order by name
    NAME             2012       2013       2014
    Desc1        5.914908  7.2918018 8.79388703
    Desc2        5.914908  7.2918018 8.79388703
    SQL> Obviously pivoting assumes you know rate_year values upfront. If not, then without pivoting:
    with t as (
               select  a.rate_type_id,
                       rate_desc,
                       rate_year,
                       rate_base_year,
                       rate_value,
                       count(*) over(partition by a.rate_type_id) cnt,
                       row_number() over(partition by a.rate_type_id order by rate_year) rn
                 from  rate_type a,
                       rates b
                 where a.rate_type_id = b.rate_type_id
        r(
          rate_type_id,
          rate_desc,
          rate_year,
          rate_base_year,
          rate_value,
          cnt,
          rn,
          result
         ) as (
                select  rate_type_id,
                        rate_desc,
                        rate_year,
                        rate_base_year,
                        rate_value,
                        cnt,
                        rn,
                        rate_base_year + rate_value + rate_base_year * rate_value * 0.01 result
                  from  t
                  where rn = 1
               union all
                select  t.rate_type_id,
                        t.rate_desc,
                        t.rate_year,
                        t.rate_base_year,
                        t.rate_value,
                        t.cnt,
                        t.rn,
                        r.result + t.rate_value + r.result * t.rate_value * 0.01 result
                  from  r,
                        t
                  where t.rate_type_id = r.rate_type_id
                    and t.rn = r.rn + 1
    select  rate_desc name,
            rate_year,
            result
      from  r
      where rn <= cnt
      order by name,
               rate_year
    NAME        RATE_YEAR     RESULT
    Desc1            2012   5.914908
    Desc1            2013  7.2918018
    Desc1            2014 8.79388703
    Desc2            2012   5.914908
    Desc2            2013  7.2918018
    Desc2            2014 8.79388703
    6 rows selected.
    SQL> SY.

  • Help with query to return results from group within table?

    Hi
    Im a total noob, so please be gentle....!
    I am looking at a table that has a WORD column and a WORD_TYPE_ID column.
    Words can have the same type_id.
    What I am trying to do is write a query that will return the longest word for each word_type_id.
    I have been trying for hours to get this and all I seem to get is either error messages or I return the longest word in the whole WORD column.
    The furthest I can get before things break down is.....
    select word
    from table
    where
    length(word) =
    select
    max(length(word))
    from table
    Any help on this or if I could be pointed in the right direction it would be greatly appreciated.
    Thanks

    Hi,
    Welcome to the forum!
    Here's one way:
    SELECT    word_type_id
    ,       MIN (word) KEEP (DENSE_RANK LAST ORDDER BY LENGTH (word))     AS longest_word
    FROM       table_x
    GROUP BY  word_type_id;If there happens to be a tie within some word_type_id (that is, 2 or more words have exactly the same length, which is the longest in that group) the expression above will return the first one, in alphabetic order. (That's what MIN means here.)
    Edited by: Frank Kulash on Aug 11, 2009 1:56 PM
    You almost had it.
    As you noticed, you were getting the longest row in the whole table. That's because your sub-query was looking at the whole table.
    If you correlate the sub-query to the row in the main table, as shown below, you can get the longest word in each group:
    select  word
    from     table     m                              -- m for main
    where      length (word) = (
                                select  max (length(word))
                   from     table
                   where     word_type_id  = m.word_type_id     -- New
                   );

  • Help with query - multiple where in grouped column

    4 columns in table named RRID1
    RRI_ID
    USER_ID
    PROCESS_TYPE
    FUNCTION
    not sure how to make this query.
    Need to pull all RRI_ID's where PROCESSTYPE ='INFO' and PROCESSTYPE ='RESOLUTION'
    for that RRI_ID.
    so same user, same RRI_ID and 2 process records, 1 INFO and 1 RESOLUTION
    so not if there is duplicate info, just if there is info and resolution.
    This is what some of data looks like..
    PROCESSTYPE|USER_ID|FUNCTION|RRI_ID
    INFO 3668 30287 817
    INFO 3748 30287 817
    INFO 4714 30287 817
    INFO 4875 30287 817
    INFO 4882 30287 817
    INFO 4885 30287 817
    INFO 3748 30288 818
    INFO 4714 30288 818
    INFO 4716 30288 818
    INFO 4882 30288 818
    INFO 4885 30288 818
    INFO 3668 30289 819
    INFO 4716 30289 819
    INFO 4875 30289 819
    INFO 4882 30289 819
    INFO 4885 30289 819
    INFO 3668 30290 820
    INFO 4716 30290 820
    INFO 4875 30290 820
    INFO 4882 30290 820
    INFO 4885 30290 820
    INFO 3668 30291 821
    INFO 4714 30291 821
    INFO 4716 30291 821
    INFO 4875 30291 821
    INFO 4882 30291 821

    you will have a stroke before you hit 40That's not the point, but thanks for your concern and you'll probably end up having a stroke sooner than me if you keep asking questions this way ;)
    Point is: stick to your original thread/question, keep it all together, be complete, instead of reposting and starting all over again.
    It's confusing when you start a new thread, while the context of your old thread matters.
    While Blu seemed to be correct, you changed the question in your previous thread after his answer and started a new one, with the same 'data'.
    Hence me being a 'nit-picker', because by starting multiple threads:
    - you'll get the right answer slower, maybe much slower
    - we're assuming things that might be out of context, given your previous thread
    etc.

  • Requesting help with a query. thx

    Hi All,
    Having some issues getting a query done.
    Please let me explain a little about our codes before starting
    What identifies an Original Case: Case_type = 10, and amend_code can be any value including null
    What identifies an re sentencing case: Case_type = 11 and amend_code can be any value, except for 10 and null
    What identifies a crack case: case_type = 11 and amend_code = 10
    SELECT      COUNT(*)
    FROM    USSC_CASES.SENTENCES S,
            USSC_CASES.SUBMISSION SUB,
            USSC_CASES.IND_SENT IND,
            USSC_CASES.DEFENDANTS DEF
    WHERE   S.SENT_ID = SUB.SENT_ID
    AND     S.DEF_ID = DEF.DEF_ID
    AND        S.SENT_ID = IND.SENT_ID
    // My problem starts here, I'm having issues coding the following in my where clause
    // if case_type = 10 and amend_code is any value, then I want to retrieve count only for original cases
    // if case_type = 11 and amend_code is any value other than 10 and null, then I want to retrieve count only for re sentencing cases.
    // if case_type = 11 and amend_code is only 10, then I want to retrieve count only for crack cases.
    // Please user variables  :CASE_TYPE and  :A_CODE which they will be acquired  by the user. Right now i am trying to get the query to work,
    // but these variables will be passed in through a procedure
    AND        ((SUB.CASE_TYPE_CODE = :CASE_TYPE AND SUB.AMEND_CODE = CASE WHEN :A_CODE IS NOT NULL THEN 10 ELSE NULL END)
    AND     TRUNC(S.SENT_VIO_DATE) BETWEEN '01-OCT-2011' AND '30-SEP-2012')
    AND     S.SENT_CREATOR_ID IS NOT NULL
    AND     SUB.SUB_TYPE_CODE = 1
    AND     SUB.STATUS_CODE = 9
    AND     S.DIST_ID <> 99
    ORDER BY S.USSC_ID, S.SENT_ID;I could take the easy way out and write 3 different queries and hard code the values but that's not what i want to do.
    using SQL developer 3.0 and oracle database 11g
    Thanks in advance
    Edited by: Rooney on Aug 14, 2012 4:44 PM

    Hi,
    Try this:
    SELECT      COUNT(*)
    FROM    USSC_CASES.SENTENCES S,
            USSC_CASES.SUBMISSION SUB,
            USSC_CASES.IND_SENT IND,
            USSC_CASES.DEFENDANTS DEF
    WHERE   S.SENT_ID = SUB.SENT_ID
    AND     S.DEF_ID = DEF.DEF_ID
    AND        S.SENT_ID = IND.SENT_ID
    // My problem starts here, I'm having issues coding the following in my where clause
    // if case_type = 10 and amend_code is any value, then I want to retrieve count only for original cases
    // if case_type = 11 and amend_code is any value other than 10 and null, then I want to retrieve count only for re sentencing cases.
    // if case_type = 11 and amend_code is only 10, then I want to retrieve count only for crack cases.
    // Please user variables  :CASE_TYPE and  :A_CODE which they will be acquired  by the user. Right now i am trying to get the query to work,
    // but these variables will be passed in through a procedure
      AND SUB.CASE_TYPE_CODE = :CASE_TYPE
    --  AND SUB.AMEND_CODE = CASE WHEN :A_CODE IS NOT NULL THEN 10 ELSE NULL END
      AND (SUB.AMEND_CODE = :A_CODE     -- THIS EXLUDES SUB.AMEND_CODE IS NULL SO THIS IS GOOD FOR BOTH  re sentencing AND crack case AND GOOD  FOR Original CASE EXCEPT FOR SUB.AMEND_CODE IS NULL
           OR (SUB.CASE_TYPE_CODE = 10 AND SUB.AMEND_CODE IS NULL AND :A_CODE IS NULL)   -- THIS ICLUDES: Original CASE AND SUB.AMEND_CODE IS NULL
    --AND TRUNC(S.SENT_VIO_DATE) BETWEEN '01-OCT-2011' AND '30-SEP-2012'  -- do not use implicite date conversion
      AND TRUNC(S.SENT_VIO_DATE) BETWEEN to_date('01-OCT-2011', 'DD-MON-YYYY')  AND TO_DATE('30-SEP-2012', 'DD-MON-YYYY')
    AND     S.SENT_CREATOR_ID IS NOT NULL
    AND     SUB.SUB_TYPE_CODE = 1
    AND     SUB.STATUS_CODE = 9
    AND     S.DIST_ID  99
    ORDER BY S.USSC_ID, S.SENT_ID;If this is not what you want you must show input table and wanted result.
    Regards,
    Peter

  • [Oracle 8i] Help with query performance

    The following query is running VERY slowly for me:
    SELECT     oord.part_nbr
    ,     sopn.ord_nbr
    ,     sopn.sub_ord_nbr
    ,     sopn.major_seq_nbr
    ,     sopn.wctr_id
    ,     sopn.oper_desc
    ,     SUM(pact.act_dlrs_earned+pact.act_brdn_dls_earned+pact.tool_dlrs_earned+pact.act_fix_brdn_dls_ea)
    ,     pact.activity_date
    FROM     PACT pact
    ,     SOPN sopn
    ,     OORD oord
    WHERE     pact.order_nbr          = sopn.ord_nbr          AND
         pact.maj_seq_nbr     = sopn.major_seq_nbr     AND
         sopn.sub_ord_nbr     = pact.sub_order_nbr     AND
         sopn.ord_nbr          = oord.ord_nbr          AND
         sopn.sub_ord_nbr     = oord.sub_ord_nbr     AND
              pact.activity_date     >= ?          AND
              sopn.rework_ind          = 'N'          AND
              (oord.part_nbr, sopn.major_seq_nbr, sopn.wctr_id)
              NOT IN     (
                        SELECT     rout.doc_nbr
                        ,     rout.major_seq_nbr
                        ,     rout.wctr_id
                        FROM ROUT rout
                        WHERE     (rout.begn_eff_dt    <=SYSDATE)     AND
                             (rout.end_eff_dt    >SYSDATE)     AND
                             (rout.po_rework_ind    ='N')       
    GROUP BY     oord.part_nbr
    ,          sopn.ord_nbr
    ,          sopn.sub_ord_nbr
    ,          sopn.major_seq_nbr
    ,          sopn.wctr_id
    ,          sopn.oper_desc
    ,          pact.activity_dateI sent a request off to my IT department (specifically asking for the explain plan and tkprof, as described in the [main post on this topic|http://forums.oracle.com/forums/thread.jspa?threadID=501834] ), and they replied with a screen shot of the 'explain plan' the tool they use (Toad) provides.
    !http://temp-sample.webs.com/explain_plan.jpg!
    I don't know if anyone can help me based off this, since I know it's not really what the main post says to provide, but it's all I was given.
    My IT department also made a few changes to my original query (see below) and told me it got rid of one of the full scans of the PACT table, but they aren't sure why it helped, and I have to say I'm suspect of any fixes where it's not understood why it helped.
    SELECT     oord.part_nbr
    ,     sopn.ord_nbr
    ,     sopn.sub_ord_nbr
    ,     sopn.major_seq_nbr
    ,     sopn.wctr_id
    ,     sopn.oper_desc
    ,     SUM(pact.act_dlrs_earned+pact.act_brdn_dls_earned+pact.tool_dlrs_earned+pact.act_fix_brdn_dls_ea)
    ,     pact.activity_date
    FROM     PACT pact
    ,     SOPN sopn
    ,     OORD oord
    WHERE     sopn.ord_nbr          = pact.order_nbr     AND
         sopn.major_seq_nbr     = pact.maj_seq_nbr     AND
         pact.sub_order_nbr     = sopn.sub_ord_nbr     AND
         oord.ord_nbr           = sopn.ord_nbr          AND
         oord.sub_ord_nbr     = sopn.sub_ord_nbr     AND
         (pact.activity_date >= ?)               AND
         'N'               = sopn.rework_ind     AND
         pact.order_nbr          = oord.ord_nbr          AND
         oord.sub_ord_nbr = pact.sub_order_nbr          AND
         (oord.part_nbr, pact.maj_seq_nbr, sopn.wctr_id) NOT IN
              SELECT /*+ INDEX_JOIN(ROUT) */     rout.doc_nbr
              ,                    rout.major_seq_nbr
              ,                    rout.wctr_id
              FROM     ROUT rout
              WHERE     rout.begn_eff_dt     <= SYSDATE     AND
                   rout.end_eff_dt      > SYSDATE     AND
                   'N' = rout.po_rework_ind
    GROUP BY     oord.part_nbr
    ,          sopn.ord_nbr
    ,          sopn.sub_ord_nbr
    ,          sopn.major_seq_nbr
    ,          sopn.wctr_id
    ,          sopn.oper_desc
    ,          pact.activity_dateAny help on this would be appreciated... when I run this (right now) for 2-3 months of data, it takes a minimum of 3 hours to complete, and I'll eventually need to run this for up to a year's worth of data.

    Hi,
    Well, let's see.
    You get 156 rows returned using IN and 121 rows using exists.
    You need identify the 'missing records' and conclude if that's correct or not, I'm not able to do that from remote, without knowing your data or system.
    It would be helpful if we could see cost and cardinalities, you (or your IT dept.) can get them easily be running the queries from your SQL*Plus prompt.
    Type
    SET AUTOTRACE TRACEONLYbefore running the queries.
    That gives you the explain plan and additional statistics (sorts in memory and sorts to disk).
    Since you use a group by, and you're on 8i can you also post results of these queries:
    select banner from v$version;
    select name, value, isdefault from v$parameter where name like '%area%';Finally, does below query give you a different plan?
    select oord.part_nbr
    ,      oord.ord_nbr
    ,      oord.sub_ord_nbr
    ,      pact.major_seq_nbr
    ,      sopn.wctr_id
    ,      sopn.oper_desc
    ,      sum(pact.act_dlrs_earned + pact.act_brdn_dls_earned + pact.tool_dlrs_earned + pact.act_fix_brdn_dls_ea)
    ,      pact.activity_date
    from   oord oord 
    ,      pact pact
    ,      sopn sopn
    where  oord.ord_nbr       = pact.order_nbr
    and    oord.sub_ord_nbr   = pact.sub_order_nbr
    and    oord.ord_nbr       = sopn.ord_nbr
    and    oord.sub_ord_nbr   = sopn.sub_ord_nbr
    and    sopn.major_seq_nbr = pact.maj_seq_nbr
    and    (pact.activity_date >= ?)
    and    'N' = sopn.rework_ind
    and    (oord.part_nbr, pact.maj_seq_nbr, sopn.wctr_id) not in ( select rout.doc_nbr
                                                                    ,      rout.major_seq_nbr
                                                                    ,      rout.wctr_id
                                                                    from   rout rout
                                                                    where  rout.begn_eff_dt <= sysdate
                                                                    and    rout.end_eff_dt > sysdate
                                                                    and    'N' = rout.po_rework_ind)
    group  by oord.part_nbr
    ,         oord.ord_nbr
    ,         oord.sub_ord_nbr
    ,         pact.major_seq_nbr
    ,         sopn.wctr_id
    ,         sopn.oper_desc
    ,         pact.activity_date

  • Help with query output

    Hello, I have the following query that I'm running in Oracle SQL Developer 1.2.1
    WITH group_by_4_column_results AS
    (SELECT m_atschunk.employee AS employee,
    SUM(CASE
    WHEN
    M_ATSCHUNK.rolloffDaysCount = '108545043' AND m_atschunk.infractiondate BETWEEN SYSDATE - 365 AND SYSDATE THEN 1 ELSE 0 END) as rolloffs,
    M_ATSCHUNK.INFRACTIONDATE + 365 as infractionDate
    FROM M_ATSCHUNK
    group by employee, infractionDate, rolloffDaysCount
    SELECT g4.*,
    SUM (rolloffs) OVER (PARTITION BY employee) AS total_rolloffs
    FROM group_by_4_column_results g4
    It will output the key elements of what I need. But where it sums up the 'total_rolloffs', I need to add that number back into the infractiondate column. Any help would be greatly appreciated.
    CREATE TABLE M_ATSCHUNK
    (EMPLOYEE varchar(50),
    ROLLOFFDAYSCOUNT varchar(3),
    INFRACTIONDATE date)
    INSERT INTO M_ATSCHUNK (EMPLOYEE, ROLLINGOFFDAYSCOUNT, INFRACTIONDATE)
    VALUES ('PHIL','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','YES', (to_date('2010/01/02 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','YES', (to_date('2010/01/03 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','YES', (to_date('2010/01/04 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','YES', (to_date('2010/01/05 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','NO', (to_date('2010/02/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('PHIL','NO', (to_date('2010/03/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','YES', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss'))),
    VALUES ('NIKI','NO', (to_date('2010/01/01 08:00:00', 'yyyy/mm/dd hh24:mi:ss')))

    Phil3061 wrote:
    I need to add that number back into the infractiondate column.Well, in general you need to use UPDATE or better MERGE. Howebver, your data sample does not show any rollofs:
    SQL> SELECT * FROM M_ATSCHUNK;
    EMPLOYEE                                           ROL INFRACTIO
    PHIL                                               YES 01-JAN-10
    PHIL                                               YES 02-JAN-10
    PHIL                                               YES 03-JAN-10
    PHIL                                               YES 04-JAN-10
    PHIL                                               YES 05-JAN-10
    PHIL                                               NO  01-FEB-10
    PHIL                                               NO  01-MAR-10
    NIKI                                               YES 01-JAN-10
    NIKI                                               YES 01-JAN-10
    NIKI                                               YES 01-JAN-10
    NIKI                                               NO  01-JAN-10
    EMPLOYEE                                           ROL INFRACTIO
    NIKI                                               NO  01-JAN-10
    NIKI                                               NO  01-JAN-10
    NIKI                                               NO  01-JAN-10
    14 rows selected.
    SQL> WITH group_by_4_column_results AS
      2  (SELECT m_atschunk.employee AS employee,
      3  SUM(CASE
      4  WHEN
      5  M_ATSCHUNK.rolloffDaysCount = '108545043' AND m_atschunk.infractiondate BETWEEN SYSDATE - 365 AND SYSDATE THEN 1 ELSE 0 END) as
    rolloffs,
      6  M_ATSCHUNK.INFRACTIONDATE + 365 as infractionDate
      7  FROM M_ATSCHUNK
      8  group by employee, infractionDate, rolloffDaysCount
      9  )
    10  SELECT g4.*,
    11  SUM (rolloffs) OVER (PARTITION BY employee) AS total_rolloffs
    12  FROM group_by_4_column_results g4
    13  /
    EMPLOYEE                                             ROLLOFFS INFRACTIO TOTAL_ROLLOFFS
    NIKI                                                        0 01-JAN-11              0
    NIKI                                                        0 01-JAN-11              0
    PHIL                                                        0 01-JAN-11              0
    PHIL                                                        0 02-JAN-11              0
    PHIL                                                        0 03-JAN-11              0
    PHIL                                                        0 04-JAN-11              0
    PHIL                                                        0 05-JAN-11              0
    PHIL                                                        0 01-FEB-11              0
    PHIL                                                        0 01-MAR-11              0
    9 rows selected.
    SQL> So adjust data sample and based on it tell us what are the expected results.
    SY.

  • Need Help With Query Using Aggregation

    If I have a table, defined like this:
    CREATE TABLE range_test
    range_id NUMBER(20) NOT NULL,
    grade CHAR(1) NOT NULL,
    lower_bound_of_range NUMBER(5,2) NOT NULL,
    upper_bound_of_range NUMBER(5,2) NOT NULL,
    received_date_time_stamp TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL
    And I wanted to query the table to find the range associated with the last inserted row for each 'grade' (e.g. 'A', 'B', 'C', etc), how would I go about that?
    I want something like the following, but I know that this won't work right:
    SELECT
    grade,
    lower_bounding_of_range,
    upper_bounding_of_range,
    max(received_date_time_stamp)
    FROM
    range_test GROUP BY received_date_time_stamp;
    Thanks for your help. . .I'm frustrating myself with this one and I think it should be possible without having to use PL/SQL (i.e. SQL aggregate functions or sub-queries should work).

    Perhaps something along the lines of...
    SQL> ed
    Wrote file afiedt.buf
      1  select deptno, empno, ename, hiredate
      2  from emp
      3* order by deptno, empno
    SQL> /
        DEPTNO      EMPNO ENAME      HIREDATE
            10       7782 CLARK      09-JUN-1981 00:00:00
            10       7839 KING       17-NOV-1981 00:00:00
            10       7934 MILLER     23-JAN-1982 00:00:00
            20       7369 SMITH      17-DEC-1980 00:00:00
            20       7566 JONES      02-APR-1981 00:00:00
            20       7788 SCOTT      19-APR-1987 00:00:00
            20       7876 ADAMS      23-MAY-1987 00:00:00
            20       7902 FORD       03-DEC-1981 00:00:00
            30       7499 ALLEN      20-FEB-1981 00:00:00
            30       7521 WARD       22-FEB-1981 00:00:00
            30       7654 MARTIN     28-SEP-1981 00:00:00
            30       7698 BLAKE      01-MAY-1981 00:00:00
            30       7844 TURNER     08-SEP-1981 00:00:00
            30       7900 JAMES      03-DEC-1981 00:00:00
    14 rows selected.
    SQL> ed
    Wrote file afiedt.buf
      1  select deptno, empno, ename, hiredate
      2  from (
      3        select deptno, empno, ename, hiredate
      4              ,row_number() over (partition by deptno order by hiredate desc) as rn
      5        from emp
      6       )
      7  where rn = 1
      8* order by deptno, empno
    SQL> /
        DEPTNO      EMPNO ENAME      HIREDATE
            10       7934 MILLER     23-JAN-1982 00:00:00
            20       7876 ADAMS      23-MAY-1987 00:00:00
            30       7900 JAMES      03-DEC-1981 00:00:00
    SQL>

  • Help with processing groups of records in database

    Ok i'm at work right now trying to finish up a project for my class and what it is is a basic class to process an inner join sql statement generated table from access and order it by the student id in order to group each student together. I have written the sql statement and logic to access the database and return the array of row objects to the command line so i know it is grouping and returning info properly. I have written the conditional if statement to get the gradePoints for A = 4, B = 3, C = 2, D = 1, and F = 0 in a class method (KEEP IN MIND THE GENERATED TABLE CONSISTS OF SID, NAME, COURSE#, COURSETITLE, AND LETTERGRADE) now I just need to process each group of students individually and calculate their overall gpa's. Here in lies the problem. I imagine i need to define current student variables as like
    currentID = s[0].getStudentID();
    currentName = s[0].getStudentName();
    then loop through the values of the array with something like
    for(int j = 0; j < s; ++j)
    if(s[j].getStudentID != currentID)
    Process the grade records for the group Then reset the
    current student to the next in line with another variable
    assignment like
    currentID = s[j].getStudentID();
    currentName = s[j].getStudentName();
    }(end of if)
    Process the row object for the student created by this loop and then add it to the output string
    } (end of for loop)
    Ok so where i need help is the logic to process the grade records for the individual groups and then processing the row object. We haven't gone over anything like this in class and it is the last thing on my list to to do so any help would be appreciated. Also, if you think i'm an idiot keep it to yourself please it's not fun for people who really need help and really would like to know for future reference how to do something to be belittled. Thanks again
    Matt
    Message was edited by:
    djmd02

    sorry i guess is hopuld explain this better...I know
    sql relatively well and the sql statement for my
    query string is rediculously long with two inner
    joins and what it returns is the sid, name,
    coursenumber, coursename, and lettergrade So if you know SQL so well, why haven't you created a ViEW using this "ridiculously long" query and made your life easier?
    Two inner joins? Nothing extraordinary about that.
    this query
    generated table is then used to populate an array of
    objects for each entry in the table. They are already
    put in order depending on sid by the sql statement
    (for example)
    11111 matt deClercq 3380 intro to java A
    11111 matt deClercq 3382 database management A
    11112 john doe 3380 intro to java A>
    and so on. The problem i am having is within the for
    loop to detect the end of each student and process
    their grades for each class and calculate the gpa for
    the whole group of grades that that student has.SQL is a declarative language, not procedural. If you're "looping", it suggests to me that you're pulling all that data into the middle tier and doing the calculation in Java.
    I'm suggesting that there's a perfectly good way to do this calculation in SQL without using your ridiculous query. You might be better served if you try and figure out what that is.
    Hope this makes things a little more clear and makes
    me look a little bit more intelligent than i seemStop worrying about what people think and concentrate on your problem. You're a student. It's unlikely that you're going to appear to be on the level of Bill Joy at this point in your career. I'd be a lot more impressed if you'd stop whining about how people perceive you.
    %

  • Need help with query joining several tables into a single return line

    what i have:
    tableA:
    puid, task
    id0, task0
    id1, task1
    id2, task2
    tableB:
    puid, seq, state
    id0, 0, foo
    id0, 1, bar
    id0, 2, me
    id1, 0, foo
    id2, 0, foo
    id2, 1, bar
    tableC:
    puid, seq, date
    id0, 0, 12/21
    id0, 1, 12/22
    id0, 2, 12/22
    id1, 0, 12/23
    id2, 0, 12/22
    id2, 1, 12/23
    what i'd like to return:
    id0, task0, 12/21, 12/22, 12/22
    id1, task1, 12/23, N/A, N/A
    id2, task2, 12/22, 12/23, N/A
    N/A doesn't mean return the string "N/A"... it just means there was no value, so we don't need anything in this column (null?)
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line...
    id0, task0, 12/21
    id0, task0, 12/22
    id0, task0, 12/23
    id1, task1, 12/23
    is this possible fairly easily?
    Edited by: user9979830 on Mar 29, 2011 10:53 AM
    Edited by: user9979830 on Mar 29, 2011 10:58 AM

    Hi,
    Welcome to the forum!
    user9979830 wrote:
    what i have:...Thanks for posting that so clearly!
    Whenever you have a question, it's even better if you post CREATE TABLE and INSERT statements for your sample data, like this:
    CREATE TABLE     tablea
    (       puid     VARCHAR2 (5)
    ,     task     VARCHAR2 (5)
    INSERT INTO tablea (puid, task) VALUES ('id0',  'task0');
    INSERT INTO tablea (puid, task) VALUES ('id1',  'task1');
    INSERT INTO tablea (puid, task) VALUES ('id2',  'task2');
    CREATE TABLE     tablec
    (       puid     VARCHAR2 (5)
    ,     seq     NUMBER (3)
    ,     dt     DATE          -- DATE is not a good column name
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  0,  DATE '2010-12-21');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  1,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id0',  2,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id1',  0,  DATE '2010-12-23');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  0,  DATE '2010-12-22');
    INSERT INTO tablec (puid, seq, dt) VALUES ('id2',  1,  DATE '2010-12-23');This way, people can re-create the problem and test their ideas.
    It doesn't look like tableb plays any role in this problem, so I didn't post it.
    Explain how you get the results from that data. For example, why do you want this row in the results:
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/21/2010 12/22/2010 12/22/2010rather than, say
    PUID  TASK  DT1        DT2        DT3
    id0   task0 12/22/2010 12/21/2010 12/22/2010? Does 12/21 have to go in the first column because it is the earliest date, or is it because 12/21 is related to the lowest seq value? Or do you even care about the order, just as long as all 3 dates are shown?
    Always say what version of Oracle you're uisng. The query below will work in Oracle 9 (and up), but starting in Oracle 11, the SELECT ... PIVOT feature could help you.
    i can get output like below through several joins, however i was hoping to condense each "id" into a single line... Condensing the output, so that there's only one line for each puid, sounds like a job for "GROUP BY puid":
    WITH     got_r_num     AS
         SELECT     puid
         ,     dt
         ,     ROW_NUMBER () OVER ( PARTITION BY  puid
                                   ORDER BY          seq          -- and/or dt
                           )         AS r_num
         FROM    tablec
    --     WHERE     ...     -- If you need any filtering, put it here
    SELECT       a.puid
    ,       a.task
    ,       MIN (CASE WHEN r.r_num = 1 THEN r.dt END)     AS dt1
    ,       MIN (CASE WHEN r.r_num = 2 THEN r.dt END)     AS dt2
    ,       MIN (CASE WHEN r.r_num = 3 THEN r.dt END)     AS dt3
    ,       MIN (CASE WHEN r.r_num = 4 THEN r.dt END)     AS dt4
    FROM       tablea    a
    JOIN       got_r_num r  ON   a.puid  = r.puid
    GROUP BY  a.puid
    ,            a.task
    ORDER BY  a.puid
    ;I'm guessing that you want the dates arranged by seq; that is, for each puid, the date related to the lowest seq comes first, regardless of whther that date is the earliest date for that puid or not. If that's not what you need, then change the analytic ORDER BY clause.
    This does not assume that the seq values are always consecutive integers (0, 1, 2, ...) for each puid. You can skip, or even duplicate values. However, if the values are always consecutive integers, starting from 0, then you could simplify this. You won't need a sub-query at all; just use seq instead of r_num in the main query.
    Here's the output I got from the query above:
    PUID  TASK  DT1        DT2        DT3        DT4
    id0   task0 12/21/2010 12/22/2010 12/22/2010
    id1   task1 12/23/2010
    id2   task2 12/22/2010 12/23/2010As posted, the query will display the first 4 dts for each puid.
    If there are fewer than 4 dts for a puid, the query will still work. It will leave some columns NULL at the end.
    If there are more than 4 dts for a puid, the query will still work. It will display the first 4, and ignore the others.
    There's nothing special about the number 4; you could make it 3, or 5, or 35, but whatever number you choose, you have to hard-code that many columns into the query, and always get that many columns of output.
    For various ways to deal with a variable number of pivoted coolumns, see the following thread:
    PL/SQL
    This question actually doesn't have anything to do with SQL*Plus; it's strictly a SQL question, and SQL questions are best posted on the "SQL and PL/SQL" forum:
    PL/SQL
    If you're not sure whether a question is more of a SQL question or a SQL*Plus question, then post it on the SQL forum. Many more people pay attention to that forum than to this one.

  • Requesting help with pivot in Oracle 10g

    Hey all,
    I have this table, let's call it table GRID that has the following columns:
    OBJECT_KEY             DATE_KEY               SEGMENT_ID             COLUMN_NAME COMMITTEDVIRTUALMEMORYSIZE_AVG
    619                    3371                   1                      M1100       593589862.4                   
    619                    3371                   1                      M1105       593611434.67                  
    620                    3371                   1                      M1100       592354508.8                   
    620                    3371                   1                      M1105       592376263.11                  
    621                    3371                   1                      M1100       731433369.6                   
    621                    3371                   1                      M1105       731455943.11What would it take to pivot the column names ('M1100', 'M1105') with the metric value volumn: 'COMMITTEDVIRTUALMEMORYSIZE_AVG' so much that this query would result in an output like this:
    OBJECT_KEY             DATE_KEY               SEGMENT_ID             M1100          M1105
    619                    3371                   1                      593589862.4     593611434.67                          
    620                    3371                   1                      592354508.8     592376263.11                          
    621                    3371                   1                      731433369.6     731455943.11Any help would be much appreciated!
    Again, Oracle 10g, not 11g so I don't have the PIVOT function to work with.
    Regards,
    TimS

    Hi,
    Search for Pivot:, or see the example below, for how to do a basic pivot. (This was called "pivot" long before Oracle 11.)
    The example below uses COUNT as the aggregate function; you'll probably wnat SUM instead.
    If you don't know how many pivoted columns there will be (two, in the example you posted), or what their unique values are ('M1100' and 'M1105') ahead of time, then you will need dynamic SQL. As dynamic SQL goes, this is pretty easy; you can do it in either SQL*Plus or PL/SQL.
    --     How to Pivot a Result Set (Display Rows as Columns)
    --     For Oracle 10, and earlier
    --     Actually, this works in any version of Oracle, but the
    --     "SELECT ... PIVOT" feature introduced in Oracle 11
    --     is better.  (See Query 2, below.)
    --     This example uses the scott.emp table.
    --     Given a query that produces three rows for every department,
    --     how can we show the same data in a query that has one row
    --     per department, and three separate columns?
    --     For example, the query below counts the number of employess
    --     in each departent that have one of three given jobs:
    PROMPT     ==========  0. Simple COUNT ... GROUP BY  ==========
    SELECT     deptno
    ,     job
    ,     COUNT (*)     AS cnt
    FROM     scott.emp
    WHERE     job     IN ('ANALYST', 'CLERK', 'MANAGER')
    GROUP BY     deptno
    ,          job;
    Output:
        DEPTNO JOB              CNT
            20 CLERK              2
            20 MANAGER            1
            30 CLERK              1
            30 MANAGER            1
            10 CLERK              1
            10 MANAGER            1
            20 ANALYST            2
    PROMPT     ==========  1. 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 = 'MANAGER' THEN 1 END)     AS manager_cnt
    FROM     scott.emp
    WHERE     job     IN ('ANALYST', 'CLERK', 'MANAGER')
    GROUP BY     deptno;
    --     Output:
        DEPTNO ANALYST_CNT  CLERK_CNT MANAGER_CNT
            30           0          1           1
            20           2          2           1
            10           0          1           1
    --     Explanation
    (1) Decide what you want the output to look like.
         (E.g. "I want a row for each department,
         and columns for deptno, analyst_cnt, clerk_cnt and manager_cnt)
    (2) Get a result set where every row identifies which row
         and which column of the output will be affected.
         In the example above, deptno identifies the row, and
         job identifies the column.
         Both deptno and job happened to be in the original table.
         That is not always the case; sometimes you have to
         compute new columns based on the original data.
    (3) Use aggregate functions and CASE (or DECODE) to produce
         the pivoted columns. 
         The CASE statement will pick
         only the rows of raw data that belong in the column.
         If each cell in the output corresponds to (at most)
         one row of input, then you can use MIN or MAX as the
         aggregate function.
         If many rows of input can be reflected in a single cell
         of output, then use SUM, COUNT, AVG, STRAGG, or some other
         aggregate function.
         GROUP BY the column that identifies rows.
    PROMPT     ==========  2. Oracle 11 PIVOT  ==========
    WITH     e     AS
    (     -- Begin sub-query e to SELECT columns for PIVOT
         SELECT     deptno
         ,     job
         FROM     scott.emp
    )     -- End sub-query e to SELECT columns for PIVOT
    SELECT     *
    FROM     e
    PIVOT     (     COUNT (*)
              FOR     job     IN     ( 'ANALYST'     AS analyst
                             , 'CLERK'     AS clerk
                             , 'MANAGER'     AS manager
    NOTES ON ORACLE 11 PIVOT:
    (1) You must use a sub-query to select the raw columns.
    An in-line view (not shown) is an example of a sub-query.
    (2) GROUP BY is implied for all columns not in the PIVOT clause.
    (3) Column aliases are optional. 
    If "AS analyst" is omitted above, the column will be called 'ANALYST' (single-quotes included).
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help with query aggregation

    Hello,
    I cannot figure out how to get the data required from this table. Can anybody help please ?
    Tablename: club_members has 3 varchar columns ( first_name, last_name and club_name )
    I am trying to summarize how many clubs each student belongs to , just showing the counts.
    Output is to look like this:
    students | clubs_per_student
    600 0
    300 1
    200 2
    Thanks for any help in advance
    Floyd

    It might help to abstract this a bit - you (seem to) have entities a and b having a many-many relationship via an intersection entity m: a <- m -> b. To get counts of a having counts of b including zero counts, you would need to drive from entity a not m, which would have no records for a with no b. You could view employees in HR as an intersection entity between departments and jobs if you restrict to employees having a department. Here are the two driving strategies in one query. I have added a job NO_DEPS to test, which the first subquery pricks up but the second doesn't.
    WITH job_int AS (
    SELECT job.job_id,
           Count (int.department_id) n_deps -- ignore the emp with null dept
      FROM jobs job
      LEFT JOIN employees int
        ON int.job_id = job.job_id
    GROUP BY job.job_id
    ), int_e AS (
    SELECT int.job_id,
           Count (department_id) n_deps -- ignore the emp with null dept
      FROM employees int
    GROUP BY int.job_id
    SELECT 'Drive from job entity' q_type, n_deps, Count (*) n_jobs
      FROM job_int
    GROUP BY n_deps
    UNION
    SELECT 'Drive from job i/s', n_deps, Count (*) n_jobs
      FROM int_e
    GROUP BY n_deps
    ORDER BY 1, 2, 3
    Q_TYPE                    N_DEPS     N_JOBS
    Drive from job entity          0          1
    Drive from job entity          1         10
    Drive from job entity          2          1
    Drive from job entity          5          5
    Drive from job entity         20          2
    Drive from job entity         29          1
    Drive from job i/s             1         10
    Drive from job i/s             2          1
    Drive from job i/s             5          5
    Drive from job i/s            20          2
    Drive from job i/s            29          1
    11 rows selected.Edited by: BrendanP on 10-May-2012 03:30
    Added test job, and fixed counting error.

Maybe you are looking for

  • Access path difference between Primary Key and Unique Index

    Hi All, Is there any specific way the oracle optimizer treats Primary key and Unique index differently? Oracle Version SQL> select * from v$version; BANNER Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production PL/SQL Release 11

  • Sql Transposing Column Name in Row

    i am using Sql Server 2008 tbl_EmployeeProfile EmployeeId EmployeeName LeaveApplicable Active 1 Sam true true 2 Rahul false false 3 Sameer true true tbl_MasterLeave id LeaveCode Description active 1 PL Paid Leave true 2 CL Casual Leave true 3 SL Sick

  • Styles and Transparent Elements (R 9.0.2)

    Hello, I want to create a portalstyle with transparent elements. Sample: My Style defindes white cellbackground. My customized LoginPortlet uses this color and covers the backgroundimage. It seems, that it is not possible to use transparency within s

  • Awful battery life after latest OTA update

    I've owned my Bionic for about 16 months now, and up until recently, have been very pleased.  After the initial Jelly Bean update, I was enjoying the best battery life I had ever experienced, up to 20+ hours with moderate use throughout the day.  How

  • Export CCA campaign to desktop

    Hi, Wanted to know if there is a way to export CCA campaign to your local desktop for version control