Analytic Query Help

My table has student grades by date. For each student, I need to return the date of the most recent F, and the number of consecutive F's the student had made at that time (NOT the total number of F's). So, for the table data below, I want the sql to return...
JANE 16-NOV-07 2
BILL 23-APR-07 4
NAME          DATE          GRADE
JANE          08-Feb-08          B
JANE          28-Dec-07          B
JANE          16-Nov-07          F
JANE          05-Oct-07          F
JANE          24-Aug-07          C
JANE          13-Jul-07          C
JANE          01-Jun-07          C
JANE          20-Apr-07          C
JANE          09-Mar-07          A
JANE          26-Jan-07          F
JANE          15-Dec-06          B
JANE          03-Nov-06          B
JANE          22-Sep-06          F
JANE          11-Aug-06          F
JANE          30-Jun-06          F
JANE          19-May-06          F
JANE          07-Apr-06          C
JANE          24-Feb-06          C
JANE          13-Jan-06          C
BILL          28-Jan-08          C
BILL          03-Dec-07          C
BILL          08-Oct-07          B
BILL          13-Aug-07          B
BILL          18-Jun-07          B
BILL          23-Apr-07          F
BILL          26-Feb-07          F
BILL          01-Jan-07          F
BILL          06-Nov-06          F
BILL          11-Sep-06          C
BILL          17-Jul-06          C
BILL          22-May-06          F
BILL          27-Mar-06          F
BILL          30-Jan-06          F

Find the Latest date of an F (over the students set of data) and then find the latest date of a NON-F within that set. Then take all records between the lower and upper (inclusive) bound.
ME_XE?    WITH Data AS
  2  (
  3     SELECT 'JANE' AS Student, TO_DATE('08-Feb-08','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
  4     SELECT 'JANE' AS Student, TO_DATE('28-Dec-07','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
  5     SELECT 'JANE' AS Student, TO_DATE('16-Nov-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
  6     SELECT 'JANE' AS Student, TO_DATE('05-Oct-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
  7     SELECT 'JANE' AS Student, TO_DATE('24-Aug-07','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
  8     SELECT 'JANE' AS Student, TO_DATE('13-Jul-07','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
  9     SELECT 'JANE' AS Student, TO_DATE('01-Jun-07','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
10     SELECT 'JANE' AS Student, TO_DATE('20-Apr-07','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
11     SELECT 'JANE' AS Student, TO_DATE('09-Mar-07','DD-MON-RR') AS Grade_date, 'A' AS Grade FROM DUAL UNION ALL
12     SELECT 'JANE' AS Student, TO_DATE('26-Jan-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
13     SELECT 'JANE' AS Student, TO_DATE('15-Dec-06','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
14     SELECT 'JANE' AS Student, TO_DATE('03-Nov-06','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
15     SELECT 'JANE' AS Student, TO_DATE('22-Sep-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
16     SELECT 'JANE' AS Student, TO_DATE('11-Aug-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
17     SELECT 'JANE' AS Student, TO_DATE('30-Jun-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
18     SELECT 'JANE' AS Student, TO_DATE('19-May-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
19     SELECT 'JANE' AS Student, TO_DATE('07-Apr-06','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
20     SELECT 'JANE' AS Student, TO_DATE('24-Feb-06','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
21     SELECT 'JANE' AS Student, TO_DATE('13-Jan-06','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
22     SELECT 'BILL' AS Student, TO_DATE('28-Jan-08','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
23     SELECT 'BILL' AS Student, TO_DATE('03-Dec-07','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
24     SELECT 'BILL' AS Student, TO_DATE('08-Oct-07','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
25     SELECT 'BILL' AS Student, TO_DATE('13-Aug-07','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
26     SELECT 'BILL' AS Student, TO_DATE('18-Jun-07','DD-MON-RR') AS Grade_date, 'B' AS Grade FROM DUAL UNION ALL
27     SELECT 'BILL' AS Student, TO_DATE('23-Apr-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
28     SELECT 'BILL' AS Student, TO_DATE('26-Feb-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
29     SELECT 'BILL' AS Student, TO_DATE('01-Jan-07','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
30     SELECT 'BILL' AS Student, TO_DATE('06-Nov-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
31     SELECT 'BILL' AS Student, TO_DATE('11-Sep-06','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
32     SELECT 'BILL' AS Student, TO_DATE('17-Jul-06','DD-MON-RR') AS Grade_date, 'C' AS Grade FROM DUAL UNION ALL
33     SELECT 'BILL' AS Student, TO_DATE('22-May-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
34     SELECT 'BILL' AS Student, TO_DATE('27-Mar-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL UNION ALL
35     SELECT 'BILL' AS Student, TO_DATE('30-Jan-06','DD-MON-RR') AS Grade_date, 'F' AS Grade FROM DUAL
36  ),
37     Max_F_Grade_date AS
38  (
39     SELECT
40        Student,
41        Grade_date,
42        Grade,
43        MAX(DECODE(Grade, 'F', Grade_date, NULL)) OVER (PARTITION BY Student) Max_F_Date,
44        MIN(DECODE(Grade, 'F', Grade_date, NULL)) OVER (PARTITION BY Student) Min_F_Date
45     FROM Data
46     ORDER BY Student, Grade_date DESC
47  ),
48     Final_set AS
49  (
50     SELECT
51        Student,
52        Grade_date,
53        Grade,
54        Max_F_Date,
55        MAX(DECODE(Grade, 'F', Min_F_Date, Grade_date)) OVER (PARTITION BY Student) Max_NON_F_Date
56     FROM Max_F_Grade_date
57     WHERE Grade_date <= Max_F_Date
58  )
59  SELECT
60     Student,
61     Max_F_Date,
62     COUNT(*)
63  FROM Final_set
64  WHERE grade_date >   Max_NON_F_Date
65  GROUP BY Student, Max_F_Date
66  /
STUDENT      MAX_F_DATE                           COUNT(*)
BILL         23-APR-2007 12 00:00                        4
JANE         16-NOV-2007 12 00:00                        2
2 rows selected.
Elapsed: 00:00:00.01

Similar Messages

  • Analytical query help

    Hi All,
    I am not able to even paste the simple of texts here , so I am trying to attach a picture ,please have a look.
    Regards
    Rahul
    Pic: http://img340.imageshack.us/i/piculj.jpg/

    WITH DATA AS
    (SELECT 'a' AS STR, '100' AS VAL FROM DUAL UNION ALL
    SELECT 'a' AS STR, '100,200' AS VAL FROM DUAL UNION ALL
    SELECT 'a' AS STR, '100,200,300' AS VAL FROM DUAL UNION ALL
    SELECT 'b' AS STR, '100' AS VAL FROM DUAL UNION ALL
    SELECT 'b' AS STR, '100,200' AS VAL FROM DUAL UNION ALL
    SELECT 'a' AS STR, '100,200,300' AS VAL FROM DUAL UNION ALL
    SELECT 'b' AS STR, '100' AS VAL FROM DUAL UNION ALL
    SELECT 'b' AS STR, '100,200' AS VAL FROM DUAL
    SELECT STR, VAL, MAXVAL FROM
    (SELECT STR, VAL, MAX(LENGTH(VAL)) OVER (PARTITION BY str) AS MAXVAL
    FROM  DATA)
    WHERE LENGTH(VAL)= MAXVALAre you want it?
    Edited by: Mahir M. Quluzade on Feb 28, 2011 5:49 PM

  • Analytic query to select next record

    Hi all,
    I would like to query the below two table match to ouput.
    1.dev_wt 2.dev_map 3.Output Result
    To help more clearance please see this image link : http://lh6.ggpht.com/_xL6eBqjW6Yo/TEqnSvlF_FI/AAAAAAAAB0U/i2sclnnaj6g/Untitled-3.jpg
    1. dev_wt
    PMS_COMP     PMS_I       PMS_PERF_D   PMS_WT   PMS_CREATION_D
    BBOARD     GICEQGROSS    04/01/2001     30     04/05/2001
    BBOARD     GICST_B       04/01/2001     5      04/05/2001
    BBOARD     SBGS_B        04/01/2001     65     04/05/2001
    BBOARD     GICEQGROSS    04/11/2001     30     04/15/2001
    BBOARD     GICST_B       04/11/2001     5      04/15/2001
    BBOARD     SBGS_B        04/11/2001     65     04/15/20012. dev_map
    GS_CODE     GS_I_CODE    GS_I_ID  MD_ID   GS_START_DT    GS_END_DT
    GICEQGROSS   CIWL        304       15     01/04/1998     31/03/2004
    GICEQGROSS   CIWL        304       2     01/04/2004      31/03/9998
    GICST_B      GICST_B     3707      15     01/04/2000     31/12/9998
    SBGS_B       SBGS_B      2231      15     01/04/1992     30/09/2003
    SBGS_B       SBGS_B      564       15     01/10/2003     31/12/9998I would like to match PMS_I = GS_CODE to retrieve GS_I_CODE and using analytic
    query to find next record.
    Because I need to select GICEQGROSS record of PMS_PERF_D date and next
    GICEQGROSS record of PMS_PERF_D from dev_wt table and put GS_WT_FR and GS_WT_TO of Output result.
    ***Date is change to YYYYMMDD format
    ***PMS_WT is devided by 100
    *3. Output Result*
    GS_I_ID    PMS_COMP     GS_I_CODE     GS_WT_FR     GS_WT_TO     GS_I_CALC
    304       BBOARD        CIWL          20010401     20010410     0.3
    3707      BBOARD        GICST_B       20010401     20010410     0.05
    5209      BBOARD        SBGS_B        20010401     20010410     0.65PMS_COMP is from dev_wt table
    GS_I_CODE is from dev_map table join with dev_wt
    GS_WT_FR is from dev_wt table of GS_START_DT
    GS_WT_TO is from dev_wt table of next record GS_START_DT where PMS_I ='GICEQGROSS'
    Now my difficulty is to select next record of PMS_PERF_D using analytic query. Below
    is my query...
    SELECT GS_I_ID, PMS_COMP, GS_I_CODE, GS_WT_FR, GS_WT_TO, GS_I_CALC
    FROM dev_wt (
    SELECT lead(PMS_PERF_D) over(partition by PMS_I order by PMS_PERF_D) as GS_WT_TO       
    FROM dev_wt where PMS_I ='GICEQGROSS')
    left join dev_map on PMS_I = GS_CODE ;Thanks
    Edited by: WinZone on Jul 24, 2010 4:46 PM
    Edited by: WinZone on Jul 24, 2010 4:50 PM

    Hi,
    This query should be fine:
    SELECT DISTINCT t2.gs_i_id, pms_comp, t2.gs_i_code,
                    TO_CHAR
                       (MIN (pms_perf_d) OVER (PARTITION BY pms_comp, pms_i),
                        'yyyymmdd'
                       ) gs_wt_fr,
                    TO_CHAR
                       (MAX (pms_perf_d) OVER (PARTITION BY pms_comp, pms_i) - 1,
                        'yyyymmdd'
                       ) gs_wt_to,
                    pms_wt / 100 gs_i_calc
               FROM dev_wt t1, dev_map t2
              WHERE t2.gs_code = t1.pms_iREM Same remark as odie: should be "2231" instead ...

  • Query Help-2

    Query Help:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
    It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
    The above was my previous posting, which was not clear..so Iam restating my problem as follows....
    I have the following tables
    Customer(custID, Name, Address)
    Order(custID, OrderID, orderDate)
    CreditCard(custID, creditCard#, creditCardType)
    Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
    Order:
    100,A001,11/22/03
    100,A002,11/24/03
    100,A003,12/02/03
    CreditCard:
    100,42323232..., VISA
    100,5234234...., MASTER
    Now how can I get
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    data in minimum no. of records....
    I think I have made my query clear..
    now please help me guys...
    thanks so much for your help.

    You are right.
    But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
    Can you please help me with the query
    if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
    With the following fields in my query result,
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    from Customer, Order, CreditCard tables
    Thanks so much for your htlp

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

  • Need a query help

    hii
    i need a query help
    i have two tables
    the 1st table will look like this
    associate id weekid no.of. hours
    4000 810 40
    4000 820 30
    4000 830 60
    4000 840 70
    2nd table will look like this
    associate id weekid no.of.hours
    4000 810 40
    4000 820 70
    4000 830 130
    4000 840 200
    so when i subtract the last two records frm each other in the second table the value should be equal to the no.of.hours in the first table.. for example
    the query shud consider the last record and one before the last record and the difference between two records shud be equal to the value in the 1st table
    for example
    consider week id 830 and 840
    in second table 830=130
    840=200
    when u subtraced both values the difference shud be equal to value in the 1st table for tht week id
    1 ---->>>> 840 - 830
    =200 - 130
    =70
    in first table 840 has 70 hrs
    like this it shud check with all records and it shud return only the records which are not equal
    regards
    srikanth

    This..?
    sql>select * from t1;
    A_ID W_ID HRS
    4000  810  40 
    4000  820  30 
    4000  830  60 
    4000  840  70 
    4000  850  80 
    sql>select * from t2;
    A_ID W_ID HRS 
    4000  810  40 
    4000  820  70 
    4000  830  130 
    4000  840  200 
    4000  850  260 
    sql>
    select a_id,w_id,hrs,sum_hrs
    from(
    select t1.a_id a_id,t1.w_id w_id,t1.hrs hrs,t2.hrs sum_hrs,
           t2.hrs - nvl(lag(t2.hrs)  over(order by t1.w_id),0) diff
    from t1,t2
    where t1.w_id = t2.w_id)
    where diff != hrs;
    A_ID W_ID HRS SUM_HRS 
    4000  850  80  260                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Analytic query !!!!

    Hi all,
    I have the following table with the set of data. This is just a short version of the actual table. The actual table has around 13 million records.
    CREATE TABLE MY_TEST_TABLE(ID NUMBER,KEY NUMBER,TYPEOFRECORD VARCHAR2(20BYTE),
    MYDATE DATE);
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values(6366556, 404887, 'GP', TO_DATE('07/23/2004 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (6366516, 404887, 'GP', TO_DATE('07/23/2004 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (6366565, 404887, 'GP', TO_DATE('07/23/2004 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (6366568, 404887, 'GP', TO_DATE('07/23/2004 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (7076940, 404887, 'CE', TO_DATE('11/04/2004 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18197564, 404887, 'CE', TO_DATE('08/29/2005 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (17561339, 404887, 'CE', TO_DATE('05/05/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18381063, 404887, 'CE', TO_DATE('05/19/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18381260, 404887, 'CE', TO_DATE('06/09/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18386869, 404887, 'CE', TO_DATE('06/10/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18895620, 404887, 'CE', TO_DATE('06/10/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (17769950, 404887, 'CE', TO_DATE('05/06/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18096803, 404887, 'CE', TO_DATE('05/19/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18381262, 404887, 'CE', TO_DATE('06/09/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    Insert into MY_TEST_TABLE(ID, KEY, TYPEOFRECORD, MYDATE)
    Values
    (18381270, 404887, 'CE', TO_DATE('06/09/2006 00:00:00', 'MM/DD/YYYY HH24:MI:SS'));
    COMMIT;
    My requirement is to get the highest ID value, TYPEOFRECORD value for a given key value. So I wrote this query:
    select KEY, max(ID) over (partition by KEY) myid, TYPEOFRECORD
    from MY_TEST_TABLE;
    but this query returns as many number of records as there are records for a particular KEY value.
    But if I write this query it gives the correct result:
    select tt1.key,tt1.id,tt1.MYDATE,tt1.TYPEOFRECORD
    from MY_TEST_TABLE tt1 where (tt1.KEY,tt1.ID) in
    (select tt.KEY, max(tt.ID) myid
    from MY_TEST_TABLE tt
    group by tt.key)
    What wrong I am doing in the analytic query.
    Thanks
    Vinayak

    you should not look for analytic, but for aggregates :
    select KEY, max(ID) id, max(TYPEOFRECORD) keep (dense_rank first order by id) typeofrecord
    from MY_TEST_TABLE
    group by key;
           KEY         ID TYPEOFRECORD
        404887   18895620 GPwith analytics, you can for each line get the max.
    like in :
    select KEY, id, TYPEOFRECORD, max(id) over (partition by key) maxid, 
    max(TYPEOFRECORD) keep (dense_rank first order by id) over (partition by key) maxTYPEOFRECORD
    from MY_TEST_TABLE;
           KEY         ID TYPEOFRECORD              MAXID MAXTYPEOFRECORD
        404887    6366556 GP                     18895620 GP
        404887   18381270 CE                     18895620 GP
        404887    6366565 GP                     18895620 GP
        404887    6366568 GP                     18895620 GP
        404887    7076940 CE                     18895620 GP
        404887   18197564 CE                     18895620 GP
        404887   17561339 CE                     18895620 GP
        404887   18381063 CE                     18895620 GP
        404887   18381260 CE                     18895620 GP
        404887   18386869 CE                     18895620 GP
        404887   18895620 CE                     18895620 GP
        404887   17769950 CE                     18895620 GP
        404887   18096803 CE                     18895620 GP
        404887   18381262 CE                     18895620 GP
        404887    6366516 GP                     18895620 GPok?

  • Query Help (Kind of Analytical query)

    Hi,
    I have a requirement in which i want to get the following output. I have taken DEPT & EMP as the example tables.
    DEPT EMPLOYEES
    10 1,2,3,4,5,6
    20 7,8,9,10
    30 11,12,13,14
    Your help will be highly appreciated.
    Regards,
    Sunil.

    Hi Gabe,
    Thanks for the quick reply. I checked the asktom site but here he has used PLSQL block to get the output.
    Is it possible to get this output using a single SQL statement.
    Thanks for the help.
    Regards,
    Sunil.

  • Help on Analytic Query

    Hi All,
    I would be thankful if you'll could provide solution to my below mentioned query.
    I have the below mentioned data.
    ENO     DT
    1     12/26/2006
    1     12/25/2006
    1     12/24/2006
    2     12/23/2006
    2     12/22/2006
    2     12/21/2006
    2     12/20/2006
    3     12/2/2006
    3     12/1/2006
    The result which I want through a query is below. The below result gives 1 row of each Eno, which are less than the Max(Dt) of each of the Eno.
    ENO     DT
    1     12/25/2006
    2     12/22/2006
    3     12/1/2006
    Also, I want to give the value 1 row dynamically, like now it is 1 row, next time it will be 2 row, 3 row and so on, and it should show me result accordingly.
    Waiting for your feedbacks and solutions.
    Regards,
    MAK

    Here is what I have.
    SQL> select * from ana_fn;
           ENO DT
             1 26-DEC-06
             1 25-DEC-06
             1 24-DEC-06
             2 23-DEC-06
             2 22-DEC-06
             2 21-DEC-06
             2 20-DEC-06
             3 19-DEC-06
             3 18-DEC-06
    9 rows selected.
    SQL>
    SQL> ed
    Wrote file afiedt.buf
      1  select * from
      2  (
      3  select eno, dt,
      4  row_number() over (partition by eno order by dt desc) rn_dt
      5  from ana_fn
      6  )
      7* where rn_dt = 2
    SQL> /
           ENO DT             RN_DT
             1 25-DEC-06          2
             2 22-DEC-06          2
             3 18-DEC-06          2And what exactly did you mean by dynamic?
    Sorry, my mistake. Had read the post wrong.
    Message was edited by:
    Keshav.B

  • Query Help on RowNum

    Hi ,
    Please help me on this…
    Select * from EMP where Emp_Type in (1, 2 ) order by Emp_Type;
    the above query gives me the result like this
    Emp_Id Name Emp_Type
    100     asas     1
    101 dsds     1
    122     gfgf     1
    154     ytytyt     1
    125     uyuy     1
    153     reree     2
    154     ytytt     2
    600     trtrtr     2
    700 gfghf 2
    If I pass the Start with num 2 and give 3 as number of records to be displayed. I need to retrieve only the following rows..
    Emp_Id Name Emp_Type
    101 dsds     1
    122     gfgf     1
    154     ytytyt     1
    154     ytytt     2
    600     trtrtr     2
    700 gfghf 2
    If the Emp_Type was only one ie,
    Select * from EMP where Emp_Type in (1) order by Emp_Type;
    I know I can get it done by using TOP-N query method
    select * from
    (Select rownum RWnum ,A.* From
    (Select * from EMP where Emp_Type in (1) order by Emp_Type) A
    where rownum<=4)
    where RWnum>=2;
    but I am stuck up with doing for multiple Emp_Type..
    here the Emp_Type could be more than two values…
    Regards
    Ben Narendran

    Hi muthukumar S,dnikiforv,Vsugur
    Thanks a lot for the analytical function ROW_NUMBER().
    But still have some concern about the query you have given..
    Let me first run the inner query.
    SQL>
    SQL > Select e.*,row_number() over(partition by Emp_Type order by Emp_Type) rno from
    EMP e where Emp_Type in (1, 2 ) order by Emp_Type;
    EMP_ID NAME EMP_TYPE RNO
    154 aaa 1 1
    101 dsds 1 2
    122 gfgf 1 3
    125 aaa 1 4
    100 asas 1 5
    700 gfghf 2 1
    600 trtrtr 2 2
    153 reree 2 3
    If I give the range from 2 and 3 am suppose to get the following rows.
    EMP_ID NAME EMP_TYPE RNO
    101 dsds 1 2
    122 gfgf 1 3
    600 trtrtr 2 2
    153 reree 2 3
    when I run the query you sent am getting the following result..
    SQL > select * from
    (Select e.*,row_number() over(partition by Emp_Type order by Emp_Type) rno from
    EMP e where Emp_Type in (1, 2 ) order by Emp_Type)
    where rno between 2 and 3;
    EMP_ID NAME EMP_TYPE RNO
    101 dsds 1 2
    154 aaa 1 3
    600 trtrtr 2 2
    700 gfghf 2 3
    Here the company id 700 is not suppose to come, instead I have to get 153.
    So I made some changes in the view and , wrote it like this
    SQL> select * from
    (select rno Rwnum,Outer_Qry.* from
    (select Real_Qry.*,row_number() over(partition by emp_type order by emp_type)rno
    from
    (select emp_id,name,emp_type from emp where emp_type in (1,2) order by emp_type)Real_Qry)Outer_Qry
    where rno <=3)
    where Rwnum >=2;
    RWNUM EMP_ID NAME EMP_TYPE RNO
    2 101 dsds 1 2
    3 122 gfgf 1 3
    2 600 trtrtr 2 2
    3 153 reree 2 3
    I guess now am getting the correct result..
    Please correct me if I am wrong, and please let me know if I have to make any modification on it..
    Thanks and regards
    Ben

  • Facing problem in implementing the analytical query in OWB

    Hi All,
    I was trying analytical function for my Customer Dimension but am not able to implement the same in my OWB.I have 2 tables who have duplicates customers which cannot be figured out by Customer id as customer id is not unique.So, i have to filter out the information on the basis of First Name, middle name, last name & DOB. Since, each customer has multiple address records( for Permanent, Correspondence, Unknown ).
    I want 1 record for all the three address types.
    Can i do thru the following query???
    If yes, how will i implment the same in OWB.
    SELECT PRENOM, MIDDLE_NAME, NOM, DEBUT, SEXE, OCCUPATION, FAMILY_STATUS,
         EDUC_QUALIFICATION, CUSTOMER_NATIONALITY, SIGLE, ANNUAL_INCOME,
         FATHER_HUSBAND_NAME,TYPE_ADDRESS, ADDRESS1, ADDRESS2, ADDRESS3,
         TOWN, REGION, POSTCODE,ADDRESS_EFFECT_DATE
    FROM
    (SELECT C1.PRENOM, C1.MIDDLE_NAME, C1.NOM, C1.DEBUT, C1.SEXE, C1.OCCUPATION, C1.FAMILY_STATUS,
         C1.EDUC_QUALIFICATION, C1.CUSTOMER_NATIONALITY, C1.SIGLE, C1.ANNUAL_INCOME,
         C1.FATHER_HUSBAND_NAME,C1.TYPE_ADDRESS, C1.ADDRESS1, C1.ADDRESS2, C1.ADDRESS3,
         C1.TOWN, C1.REGION, C1.POSTCODE,C1.ADDRESS_EFFECT_DATE,
    ROW_NUMBER() OVER (PARTITION BY C1.PRENOM, C1.MIDDLE_NAME, C1.NOM, C1.DEBUT,C1.TYPE_ADDRESS
    ORDER BY C1.ADDRESS_EFFECT_DATE DESC)M
    FROM CUST_1 C1
    UNION ALL
    SELECT C1.PR_FIRST_NM, C1.PR_MIDDLE_NM, C1.PR_LAST_NM, C1.PR_DOB, C1.PR_GENDER, C1.PR_OCCUPATION, C1.PR_MARITAL_STATUS,
    C1.PR_EDUCATION_QUAL, C1.PR_NATIONALITY, C1.PR_TITLE, C1.GP_ANNUAL_INC, C1.PR_FATHER_NM,
    C1.AD_TYPE, C1.AD_ADDR1, C1.AD_ADDR2, C1.AD_ADDR3, C1.TOWN, C1.REGION, C1.AD_PIN_CD,C1.REC_UPDT_DT,
    ROW_NUMBER() OVER (PARTITION BY C1.PR_FIRST_NM, C1.PR_MIDDLE_NM, C1.PR_LAST_NM, C1.PR_DOB,C1.AD_TYPE
    ORDER BY C1.REC_UPDT_DT DESC )M
    FROM CUST_2 C1)
    WHERE M = 1
    Please help me out as right now, am using aggregators which are taking lot of time. Loading type on my Customer Dimension table is- Insert/Update
    Thanks in advance
    -Nikita.

    Hello Nikita,
    From your first post I understand that you would like to merge 3 similar (but not complete identical) records into 1 record. If this is the case, then have you thought about using the match-merge operator in OWB?
    With the match-merge operator you can tell the mapping which records are similar by selecting "first_nm", "middle_nm", "last_nm" in the Match-Bin of the operator.
    Then you define how attributes should be merged.
    This way you do not need to aggregate your source data set. Just select all records from both source tables. Put those in the Set-Operator "UNION ALL" and this will be you input for the match-merge operator.
    Regards,
    Ilona

  • Bucket query help

    create table rangespendbucket(rangespend varchar2(40), id number)
    insert into rangespendbucket values('100-200',1);
    insert into rangespendbucket values('200-500',2);
    insert into rangespendbucket values('500-1000',3);
    insert into rangespendbucket values('1000-',4);
    commit;
    create table spend(supplier varchar2(40), cy_spend number)
    insert into spend values('A',100);
    insert into spend values('B',25);
    insert into spend values('C',30);
    insert into spend values('D',1000);
    insert into spend values('E',10);
    insert into spend values('A',200);
    insert into spend values('F',0);
    insert into spend values('E',20);
    insert into spend values('C',540);
    insert into spend values('B',300);
    insert into spend values('A',300);
    insert into spend values('C',10);
    insert into spend values('B',0);
    insert into spend values('E',0);
    insert into spend values('G',90);
    insert into spend values('H',0);
    insert into spend values('A',0);
    insert into spend values('P',7000);
    commit;
    i am new in this forums . some one in my company given me the following query/task.
    I want find out all those in a single query(1-8) except 1.1(separatee query).
    we are using oracke 10g reaalese 2 version.
    1)no of customer/supplier in the spend bucket.
    1.1. If anybody clcik on that particular bucket it will show no of suppliers.
    2)total no of supplier for all bucket(sum)
    3)% of supplier for each bucket.(each bucket supp cnt *100/total supp cnt)
    3)total spend for each bucket
    4)total spend for all combination of bucket
    5)% of spend for each bucket than total bucket(each bucket supp spend *100/total supp spend)
    6)how many no of suppliers make 80% of total spend(respect to all bucket)
    7)how many no of suppliers make 20% of total spend(respect to all bucket)
    8)top 3 suppliers make how much % of spend(respect to all bucket)
    i am eagerly requesting to all of you please help me to making this query.
    this query is required for making dashboard.
    column name should be like this-totalsupplierscnt__all_bucket,'cnt suppliers 100-200','%cnt suppliers 100-200','cnt supplier 200-500','%cnt supplier 200-500',
    'cnt supplier 500-1000','%cnt supplier 500-1000','cnt suppliers 1000-','%cnt suppliers 1000-',
    totalsuppliersspend_all_bucket,'spend for 100-200','%spend for 100-200','spend for 200-500','%spend for 200-500',
    'spend for 500-1000','%spend for 500-1000','spend for 1000-','%spend for 1000-',
    'no of supplierss 80% of total spend'(calculation-suppose total spend 100. spend sorted by decending 80% of total spend may cover 1-2 suppliers),
    'no of supplierss 20% of total spend'(calculation- total no of suppliers- no of suppliers making 80% spend),
    'top 3 suppliers spend'(calculation-spend sorted by desc,if we get total spend then we calculate -top3'spend*100/total spend)
    if you want much more clarification i will give you.
    Edited by: 949497 on Jul 27, 2012 7:51 PM
    Edited by: 949497 on Jul 27, 2012 8:11 PM

    Hi,
    Welcoem to the forum!
    949497 wrote:
    create table rangebucket(rangespend varchar2(40), id number) ...Thanks for posting the CREATE TABLE and INSERT statements; that's very helpful!
    i am new in this forums ....You're way ahead of some people, who have been using the forum for years but still haven't learned how to post their data.
    Don't forget to post the exact results you want from that data.
    How are the two tables related? Do you have to parse rangebucket.rangespend to extract the NUMBERs 100 and 200 from the VARCHAR2 '100-200'? It would be simpler to do it the other way around: store the NUMBERs 100 and 200 in two separate NUMBER columns, and derive the label '100-200' from them (or store the label in a separate column, as it is now, in addition to rangebegin and rangeened NUMBER columns).
    Whatever number is related to these ranges, what happens if that number is exactly 200? What if it is less than 100?
    >
    I want find out all those in a single query(1-8) except 1.1(separatee query).
    we are using oracke 10g reaalese 2 version.Thanks! That's another thing that's always imoportant (and another thing some people haven't learned to do).
    1)no of customer/supplier in the spend bucket.
    1.1. If anybody clcik on that particular bucket it will show no of suppliers.This is the SQL and PL/SQL forum. What do you mean by "click", and how does it involve SQL or PL/SQL?
    2)total no of supplier for all bucket(sum)
    3)% of supplier for each bucket.(each bucket supp cnt *100/total supp cnt)
    3)total spend for each bucket
    4)total spend for all combination of bucket
    5)% of spend for each bucket than total bucket(each bucket supp spend *100/total supp spend)
    6)how many no of suppliers make 80% of total spend(respect to all bucket)I'm not certain I understand what any of the outputs are, but I'm especially unsure of 6) and 7).
    Do you want the smallest possible number of suppliers, such that their spend totals account for at least 80% of all spend total?
    Do you want the largest possible number of suppliers, such that their sepnd total just barely exceeds 80% of the overall total?
    Do you want something else entirely?
    When you post the results you want from the given sample data, explain this part very carefully.
    7)how many no of suppliers make 20% of total spend(respect to all bucket)
    8)top 3 suppliers make how much % of spend(respect to all bucket)I suspect you'll need to use aggregate functions to get the total by suppliers, and then use analytic fucntions to answer questions such as "Is the running total greater than 80% yet?". I'm sure this will be clearer after you post the results you want.

  • Query help on Goods Receipt Query with AP Invoice

    Looking for a little help on a query.  I would like to list all the goods receipts for a given date range and then display the AP Invoice information (if its been copied to an AP Invoice).  I think my problem is in my where clause, I plagerized an SAP query to show GR and AP from a PO as a start.  SBO 2005 SP01.  Any help would be great appreciated.  Thanks
    SELECT distinct 'GR',
    D0.DocStatus,
    D0.DocNum ,
    D0.DocDate,
    D0.DocDueDate,
    D0.DocTotal,
    'AP',
    I0.DocStatus,
    I0.DocNum ,
    I0.DocDate,
    I0.DocDueDate,
    I0.DocTotal,
    I0.PaidToDate
    FROM
    ((OPDN  D0 inner Join PDN1 D1 on D0.DocEntry = D1.DocEntry)
    full outer join
    (OPCH I0 inner join PCH1 I1 on I0.DocEntry = I1.DocEntry)
    on (I1.BaseType=20 AND D1.DocEntry = I1.BaseEntry AND D1.LineNum=I1.BaseLine))
    WHERE
    (D1.BaseType=22 AND D1.DocDate>='[%0]' AND D1.DocDate<='[%1]')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry
    FROM PDN1 WHERE BaseType=22 AND DocDate>='[%0]' AND DocDate<='[%1]'))

    Hi Dalen ,
    I  believe it is because of the condition
    (D1.BaseType=22 AND D1.DocDate>='%0' AND D1.DocDate<='%1')
    OR (I1.BaseType=20 AND I1.BaseEntry IN
    (SELECT Distinct DocEntry FROM PDN1 WHERE PDN1.BaseType=22 AND DocDate>='%0' AND DocDate<='%1'))
    Try changing
    D1.BaseType=22 OR D1.DocDate>='%0' AND D1.DocDate<='%1
    PDN1.BaseType=22 OR DocDate>='%0' AND DocDate<='%1'))
    Lets see what would be the result . Lets have some fun with troubleshooting
    See what would be the difference in the result .
    Thank you
    Bishal

  • Query help: query to return column that represents multiple rows

    I have a table with a name and location column. The same name can occur multiple times with any arbitrary location, i.e. duplicates are allowed.
    I need a query to find all names that occur in both of two separate locations.
    For example,
    bob usa
    bob mexico
    dot mexico
    dot europe
    hal usa
    hal europe
    sal usa
    sal mexico
    The query in question, if given the locations usa and mexico, would return bob and sal.
    Thanks for any help or advice,
    -=beeky

    How about this?
    SELECT  NAME
    FROM    <LOCATIONS_TABLE>
    WHERE   LOCATION IN ('usa','mexico')
    GROUP BY NAME
    HAVING COUNT(DISTINCT LOCATION) >= 2Results:
    SQL> WITH person_locations AS
      2  (
      3          SELECT 'bob' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      4          SELECT 'bob' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      5          SELECT 'dot' AS NAME, 'Mexico' AS LOCATION FROM DUAL UNION ALL
      6          SELECT 'dot' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      7          SELECT 'hal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
      8          SELECT 'hal' AS NAME, 'Europe' AS LOCATION FROM DUAL UNION ALL
      9          SELECT 'sal' AS NAME, 'USA' AS LOCATION FROM DUAL UNION ALL
    10          SELECT 'sal' AS NAME, 'Mexico' AS LOCATION FROM DUAL
    11  )
    12  SELECT  NAME
    13  FROM    person_locations
    14  WHERE   LOCATION IN ('USA','Mexico')
    15  GROUP BY NAME
    16  HAVING COUNT(DISTINCT LOCATION) >= 2
    17  /
    NAM
    bob
    salHTH!
    Edited by: Centinul on Oct 15, 2009 2:25 PM
    Added sample results.

  • QUERY HELP!!! trying to create a query

    i'm creating a summary report
    i have a table with sale dates
    for example i have a table tab_1 and column saleDate as
    saleDat
    1923
    1936
    1945
    2003
    2005
    saleDate contains years and there are some missing years where no sale
    was made
    My report has to display years starting from earliest year
    so i have to create a query that starts with 1923
    but the problem is that I have to have years that are not in table.
    for example i have to display years 1924 which is not in table
    so the part of report has to look like
    1923 blah blah summary.........
    1924 "
    1925
    1926
    2005
    2006
    upto current year (2006 may not be in the table, but i have to display)
    i just need to know the query that can query all the years starting from
    the ealiest saleDate to current year
    thanks in advance

    Please write the query in the following form:
    SELECT a.year, --- place other columns from your table.
    FROM (SELECT (:start_num + rownum) year
    FROM all_tab_columns
    WHERE :start_num + rownum <= :end_num) a,
    tab_1 b
    WHERE a.year = b.saleDat(+);
    Note:
    1) if your start year and end year are 1923 and 2006. Then input as below:
    :start_num = 1922
    :end_num = 2006
    2) Since for some of the years (1924 etc) may not be there in your so you may need to use NVL to print proper indicators.
    3) If you have more than one record in tab_1 for a particular year then group them based year and then use it.
    Hope this helps.
    - Saumen.

Maybe you are looking for

  • PE 10 missing audio from *.avi files?

    Hi,   New PE 10 installation.  When I add a *.avi file to the timeline or sceneline, I am missing the audio tracks. Don't see the audio tracks.  Even when I press the Play button above, there is only video and no audio.  But in the Media section, whe

  • Hp photosmart pro b8350

    i have just got new laptop it a sony vaio full hd and have set printer to it ,but when i print pics they come out to dark,on old pc they are perfect thats on vista im now on windows 7 , when i put it on new pc it found latest drivers and installed on

  • Av adapter problem.

    After I updated to ios7 I got  "downloading accessory firmware" when I plug in the adapter but nothing works. Need help ;-)

  • Nokia 2630 problems

    1. I have set an alarm for 24/11 on 23/11 and the alarm sound was heard on 23/11 after I had selected Save and went through the options. 2. I received a phone call, and I couldn't hear anything from the caller; also the phone started behaving strange

  • Where can i get basic overveiw on BPC

    Hi, can any one giude me getting details about BPC and Overveiw... Thanks