SQL Help Need to Calculate Count beteen two dates.

CREATE TABLE SUPPORT_SERVICES.LOAN_ACTION
  LOAN_NBR     NUMBER(10),
  ACTION_CODE  VARCHAR2(20 BYTE),
  DOC_CODE     VARCHAR2(20 BYTE),
  ACTION_DATE  DATE
SET DEFINE OFF;
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'ASSIGN', 'MORT', TO_DATE('12/01/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'PASSIGN', 'MORT', TO_DATE('12/02/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'QASSIGN', 'MORT', TO_DATE('12/03/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'RASSIGN', 'MORT', TO_DATE('12/09/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'SASSIGN', 'MORT', TO_DATE('12/04/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'TASSIGN', 'MORT', TO_DATE('12/05/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'UASSIGN', 'MORT', TO_DATE('12/06/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'YASSIGN', 'MORT', TO_DATE('12/07/2011 20:24:38', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (100, 'xASSIGN', 'MORT', TO_DATE('12/08/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'ASSIGN', 'MORT', TO_DATE('12/01/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'PASSIGN', 'MORT', TO_DATE('12/02/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'QASSIGN', 'MORT', TO_DATE('12/03/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'SASSIGN', 'MORT', TO_DATE('12/04/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'TASSIGN', 'MORT', TO_DATE('12/05/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'UASSIGN', 'MORT', TO_DATE('12/06/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'YASSIGN', 'MORT', TO_DATE('12/07/2011 20:24:39', 'MM/DD/YYYY HH24:MI:SS'));
Insert into LOAN_ACTION
   (LOAN_NBR, ACTION_CODE, DOC_CODE, ACTION_DATE)
Values
   (101, 'UNASSIGN', 'MORT', TO_DATE('12/08/2011 20:24:40', 'MM/DD/YYYY HH24:MI:SS'));
COMMIT;Could some one please give me a idea to solve following scenario .
from the above table i want to count DOC_CODE column values between action_code ='ASSIGN' AND action_code 'UNASSIGN'
example :
LOAN_NBR     ACTION_CODE     DOC_CODE        ACTION_DATE
101     ASSIGN                     MORT     12/1/2011 8:24:39 PM
101     PASSIGN                     MORT     12/2/2011 8:24:39 PM
101     QASSIGN                   MORT     12/3/2011 8:24:39 PM
101     SASSIGN                     MORT     12/4/2011 8:24:39 PM
101     TASSIGN                     MORT     12/5/2011 8:24:39 PM
101     UASSIGN                     MORT     12/6/2011 8:24:39 PM
101     YASSIGN                     MORT     12/7/2011 8:24:39 PM
101     UNASSIGN                     MORT     12/8/2011 8:24:40 PMFor Loan Number 101 ,ACTION_CODE='ASSIGN' was on 12/1/2011 and ACTION_CODE='UNASSIGN' was on 12/6/2011
so now the doc_count is 4 ;
Let me know if you need any additioanl infoamtion on this.
Thank you
Vijay

Hi, Vijay,
Thanks for posting the CREATE TABLE and INSERT statements.
Don't forget to post the full results you want from that sample data, nor to say which version of Oracle you're using. (It probably doesn't matter this time; the query below works in Oracle 8.1 and higher.)
vijayp wrote:
from the above table i want to count DOC_CODE column values between action_code ='ASSIGN' AND action_code 'UNASSIGN'
example :
LOAN_NBR     ACTION_CODE     DOC_CODE        ACTION_DATE
101     ASSIGN                     MORT     12/1/2011 8:24:39 PM
101     PASSIGN                     MORT     12/2/2011 8:24:39 PM
101     QASSIGN                   MORT     12/3/2011 8:24:39 PM
101     SASSIGN                     MORT     12/4/2011 8:24:39 PM
101     TASSIGN                     MORT     12/5/2011 8:24:39 PM
101     UASSIGN                     MORT     12/6/2011 8:24:39 PM
101     YASSIGN                     MORT     12/7/2011 8:24:39 PM
101     UNASSIGN                     MORT     12/8/2011 8:24:40 PMFor Loan Number 101 ,ACTION_CODE='ASSIGN' was on 12/1/2011 and ACTION_CODE='UNASSIGN' was on 12/6/2011
so now the doc_count is 4 ;U<b>N</b>ASSIGN was on 12/8.
UASSIGN (with no N before the end) was on 12/6.
>
Let me know if you need any additioanl infoamtion on this.What if either ASSIGN or UASSIGN occurs more than once for the same loan_nbr? The query below uses the earliest ASSIGN date and the latest UASSIGN date.
Thank you
Vijay
WITH     got_date_range     AS
     SELECT     loan_nbr, doc_code, action_date
     ,     MIN ( CASE
                    WHEN  action_code = 'ASSIGN'
                 THEN  action_date
                END
              ) OVER (PARTITION BY  loan_nbr)     AS assign_date
     ,     MAX ( CASE
                    WHEN  action_code = 'UASSIGN'
                 THEN  action_date
                END
              ) OVER (PARTITION BY  loan_nbr)     AS uassign_date
     FROM    loan_action
SELECT       loan_nbr
,       COUNT (doc_code)     AS cnt_doc_code
FROM       got_date_range
WHERE       action_date     > assign_date
AND       action_date     < uassign_date
GROUP BY  loan_nbr
;

Similar Messages

  • Calculate difference between two dates/times

    Hi all,
    Is there any function module to calculate difference between two dates/times which are in TIMESTAMPL format.
    I need to know how many millisconde(second,minutes, hours... )there is between these two times.
    Please, It is urgent
    Thank you all.
    Karim

    hi,
    try the following function
    CALL FUNCTION 'CCU_TIMESTAMP_DIFFERENCE'        
          EXPORTING                                  
               timestamp1 = timestamp1               
               timestamp2 = timestamp2               
          IMPORTING                                  
               difference = diff                     
          EXCEPTIONS                                 
               OTHERS     = 1. 
    the above function gives the difference in seconds...
    try the following  code to set the resolution to milliseconds..
    SET RUN TIME CLOCK RESOLUTION LOW
    check the thread for details:
    SET RUN TIME CLOCK RESOLUTION?
    all the best!!!
    Regards,
    Aparna

  • How to calculate days between two DATES

    How to calculate days between two DATES ?
    which is the functional module for that ?
    help me

    Hi,
    use function module : it works,
    HR_HK_DIFF_BT_2_DATES
    give output format = 03 and get the value in days.
    code is as below :
    data : DATE1 type P0001-BEGDA,
    DATE2 type P0001-BEGDA,
    YEARS type P0347-SCRYY,
    MONTHS type P0347-SCRMM,
    DAYS type P0347-SCRDD.
    date1 = '20070331'.
    date2 = '20070101'.
    CALL FUNCTION 'HR_HK_DIFF_BT_2_DATES'
    EXPORTING
    DATE1 = date1
    DATE2 = date2
    OUTPUT_FORMAT = '03'
    IMPORTING
    YEARS = years
    MONTHS = months
    DAYS = days
    EXCEPTIONS
    INVALID_DATES_SPECIFIED = 1
    OTHERS = 2
    IF SY-SUBRC <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
    WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    write : days.
    Reward points, if helpful,
    Regards,
    Sandeep Kaushik

  • Count between two dates.

    dear friends
    i want fetch count between two dates.
    my query is like below.
    SELECT (to_date('19-mar-2012','dd-mm-yyyy')-to_date('01-apr-2012','dd-mm-yyyy')) FROM dual
    its given out like -13 but i want in positive mod like 13 only not '-' Sign.

    just use abs() function to your query to get the positive value
    SELECT abs(to_date('19-mar-2012','dd-mm-yyyy')-to_date('01-apr-2012','dd-mm-yyyy')) diff FROM dual

  • Need Help on List of Months between Two Dates

    Hello everyone,
    I have a table which has startdate & enddate, and need a SELECT statement to list all months between these two dates for each given ID.
    I did some test, and could not figure out how to get the startdate & enddate from testing table (instead of hard code them) in the select statement.
    Could anybody please help on it (Oracle 11gR2),
    Thanks in advance!!!
    create table testing(
    id          number,
    start_date  date,
    end_date    date);
    insert into testing values(100, to_date('05-FEB-2011', 'DD-MON-YYYY'), to_date('28-MAY-2011', 'DD-MON-YYYY'));
    insert into testing values(200, to_date('20-JUN-2011', 'DD-MON-YYYY'), to_date('28-DEC-2011', 'DD-MON-YYYY'));
    commit;
    select * from testing;
            ID START_DAT END_DATE
           100 05-FEB-11 28-MAY-11
           200 20-JUN-11 28-DEC-11
    Elapsed: 00:00:00.01
    *for testing.id = 100:*
    select to_char(add_months(to_date('05-FEB-2011', 'DD-MON-YYYY'), l - 1), 'YYYY-Mon') Dates
    from (select level l
           from dual
        connect by level <= months_between(trunc(to_date('28-MAY-2011', 'DD-MON-YYYY'), 'MONTH'),
                                           trunc(to_date('05-FEB-2011', 'DD-MON-YYYY'), 'MONTH')) + 1);
    DATES
    2011-Feb
    2011-Mar
    2011-Apr
    2011-May
    Elapsed: 00:00:00.01
    *for testing.id = 200:*
    select to_char(add_months(to_date('20-JUN-2011', 'DD-MON-YYYY'), l - 1), 'YYYY-Mon') Dates
    from (select level l
           from dual
        connect by level <= months_between(trunc(to_date('28-DEC-2011', 'DD-MON-YYYY'), 'MONTH'),
                                           trunc(to_date('20-JUN-2011', 'DD-MON-YYYY'), 'MONTH')) + 1);
    DATES
    2011-Jun
    2011-Jul
    2011-Aug
    2011-Sep
    2011-Oct
    2011-Nov
    2011-Dec
    7 rows selected.

    SQL> select * from testing
      2  /
            ID START_DAT END_DATE
           100 05-FEB-11 28-MAY-11
           200 20-JUN-11 28-DEC-11
    SQL> select  id,
      2          to_char(add_months(start_date,column_value - 1),'YYYY-Mon') dates
      3    from  testing,
      4          table(
      5                cast(
      6                     multiset(
      7                              select  level
      8                                from  dual
      9                                connect by add_months(trunc(start_date,'MM'),level - 1) <= end_date
    10                             )
    11                     as sys.OdciNumberList
    12                    )
    13               )
    14    order by id,
    15             column_value
    16  /
            ID DATES
           100 2011-Feb
           100 2011-Mar
           100 2011-Apr
           100 2011-May
           200 2011-Jun
           200 2011-Jul
           200 2011-Aug
           200 2011-Sep
           200 2011-Oct
           200 2011-Nov
           200 2011-Dec
    11 rows selected.
    SQL> SY.

  • Javascript anomoly on day count between two dates

    Using ApEx 4.0, I have found an anomoly in some javascript code that calculates the number of days between two dates, the current_date and the past_date. If the past-date is on or before March 10, 2013, and the current_date is between March 10, 2013, and November 3, 2013, the day count will be 1 day less than the actual count. Between November 3, 2013, and November 4, 2013, the count increments by 2, and then the count will be accurate from this date forward.
    Here are examples:
    Mar 10, 2013 = 69 days from 31-DEC-2012
    Mar 11, 2013 = 69 days from 31-DEC-2012
    Mar 12, 2013 = 70 days from 31-DEC-2012
    Nov. 3 2013 = 306 days from 31-DEC-2012
    Nov. 4 2013 = 308 days from 31-DEC-2012
    March 11 should be 70, and March 12 should be 71. November 3 should be 307, and November 4 corrects the wrong count which began March 11.
    Changing the past_date to March 10, 2013 produces the following:
    10-Mar-2013 = 0 days from 10-Mar-2013
    11-Mar-2013 = 0 days from 10-Mar-2013
    12-Mar-2013 = 1 days from 10-Mar-2013
    But changing the past_date to March 11, 2013, produces correct numbers:
    11-Mar-2013 = 0 days from 11-Mar-2013
    12-Mar-2013 = 1 days from 11-Mar-2013
    13-Mar-2013 = 2 days from 11-Mar-2013
    I would certainly appreciate anyone's help on identifying the cause of this anomoly. Here is the javascript code:
    var w1= ($v("P48_PAST_DATE"));
    w1 = (w1.toString());
    var vmon = (w1.substr(3,3));
    var vyr = (w1.substr(7));
    var r = (vyr.length);
    if (r == 2)
    vyr = (parseFloat(vyr) + 2000);
    var vday = (w1.substr(0,2));
    var y = (vmon.concat(" ",vday,", ",vyr));
    y = Date.parse(y);
    var w2 = ($v("P48_CURRENT_DATE"));
    var vmon2 = (w2.substr(3,3));
    var vyr2 = (w2.substr(7));
    var vday2 = (w2.substr(0,2));
    var x = (vmon2.concat(" ",vday2,", ",vyr2));
    x = Date.parse(x);
    var numdays = (x - y);
    numdays = (Math.floor(numdays / 86400000));
    $s("P48_NUMBEROFDAYS",numdays);

    Did you google for something like "javascript number of days between two dates". I think you will find the explanation in this observation:
    This method doesn't work properly if there's a daylight savings jump between the two dates.
    There are examples to be found to calculate the difference between two dates.

  • How to Calculate second between two dates?

    I'm wish to create a ref ID using seconds between two dates as the uniue number. I usually use DateDiff function in VB to calculate the ref ID. But now instead developing using VB, i'm using java in developing my project. I wonder is there any class similar to the datediff function? Please advice.Thank you

    diff_sec =( Date1.getSeconds() - Date2.getSeconds());

  • PROBLEM IN GETTING MONTHLY OPENING & ENDING BALANCE BETEEN TWO DATES

    Hi,
    i m executing this query to get following result.
    OB is function through which i m getting Opening qty at time '01-JAN-2005' .
    QTYIN is qty purchased.
    QTYOUT is qty sold.
    END_BAL is difference of (OPENING_BALANCE+ QTYIN) - QTYOUT.
    PNAME is product name.
    SELECT ALL
    TO_CHAR(STKTRAN.SDATE,'MON,YY') MON,
    PRODUCTS.PNAME,
    OB(PID,'01-OCT-2005') OB_BAL,
    SUM(STKTRAN.QTYIN) QTYIN,
    SUM(STKTRAN.QTYOUT) OUT,
    END_BAL(PID,31-OCT-2005) END_BAL
    FROM PRODUCTS, STKTRAN
    WHERE PRODUCTS.PID = STKTRAN.PID
    AND STKTRAN.SDATE BETWEEN '01-OCT-2005' AND '31-OCT-2005'
    GROUP BY
    TO_CHAR(STKTRAN.SDATE,'MON,YY'), PRODUCTS.PNAME;
    MON PNAME OB QTYIN OUT BAL
    OCT,05 GX-150 1000 18655 12300 7355
    OCT,05 GX-220 0 20500 18245 2255
    opening balance is the qty_in_stock + qty_purchased - qty_sold before 01-oct-05.
    ending balance is the qty_in_stock + qty_purchased - qty_sold before 01-nov-05.
    the problem is i want to get result between two dates. suppose between
    01-jan-05 and 31-dec-05 group by month n product.
    "one month ending balance should be the opening balance of other. " ???
    means it will look like ....
    MON PNAME OB QTYIN OUT BAL
    OCT,05 GX-150 1000 18655 12300 7355
    OCT,05 GX-220 0 20500 18245 2255
    NOV,05 GX-150 7355 1000 5355 3355
    NOV,05 GX-220 2255 1000 1255 2255
    please guide me ......thanks

    If you have 8i enterprise edition, then analytic functions are supported and you could use this solution:
    SQL> create table products
      2  as
      3  select 1 pid, 'GX-150' pname from dual union all
      4  select 2, 'GX-220' from dual
      5  /
    Tabel is aangemaakt.
    SQL> create table stktran
      2  as
      3  select date '2005-01-20' sdate, 1 pid, 1000 qtyin, 0 qtyout from dual union all
      4  select date '2005-10-10', 1, 18655, 12300 from dual union all
      5  select date '2005-10-10', 2, 10500, 10000 from dual union all
      6  select date '2005-10-20', 2, 10000, 8245 from dual union all
      7  select date '2005-11-11', 1, 1000, 5355 from dual union all
      8  select date '2005-11-11', 2, 1000, 1255 from dual
      9  /
    Tabel is aangemaakt.
    SQL> var P_STARTDATE varchar2(10)
    SQL> var P_ENDDATE varchar2(10)
    SQL> exec :P_STARTDATE := '01-01-2005'
    PL/SQL-procedure is geslaagd.
    SQL> exec :P_ENDDATE := '31-12-2005'
    PL/SQL-procedure is geslaagd.
    SQL> select pname
      2       , to_char(m,'MON,yy') mon
      3       , lag(eb,1,0) over (partition by pname order by m) ob
      4       , qtyin
      5       , qtyout
      6       , eb
      7    from ( select pname
      8                , mon m
      9                , qtyin
    10                , qtyout
    11                ,   sum(nvl(qtyin,0)) over (partition by pname order by mon)
    12                  - sum(nvl(qtyout,0)) over (partition by pname order by mon) eb
    13             from ( select pname
    14                         , trunc(sdate,'mm') mon
    15                         , sum(qtyin) qtyin
    16                         , sum(qtyout) qtyout
    17                      from ( select p.pname
    18                                  , s.sdate
    19                                  , s.qtyin
    20                                  , s.qtyout
    21                               from products p
    22                                  , stktran s
    23                              where s.pid = p.pid
    24                                and s.sdate between to_date(:P_STARTDATE,'dd-mm-yyyy') and to_date(:P_ENDDATE,'dd-mm-yyyy')
    25                             union all
    26                             select pname
    27                                  , mon
    28                                  , null
    29                                  , null
    30                               from ( select add_months(trunc(to_date(:P_STARTDATE,'dd-mm-yyyy'),'mm'),level-1) mon
    31                                        from dual
    32                                     connect by level <=
    33                                             months_between
    34                                             ( trunc(to_date(:P_ENDDATE,'dd-mm-yyyy'))
    35                                             , trunc(to_date(:P_STARTDATE,'dd-mm-yyyy'))
    36                                             ) + 1
    37                                    )
    38                                  , ( select pid
    39                                           , pname
    40                                        from products
    41                                    )
    42                           )
    43                     group by pname
    44                         , trunc(sdate,'mm')
    45                  )
    46         )
    47   order by m
    48       , pname
    49  /
    PNAME  MON            OB      QTYIN     QTYOUT         EB
    GX-150 JAN,05          0       1000          0       1000
    GX-220 JAN,05          0                                0
    GX-150 FEB,05       1000                             1000
    GX-220 FEB,05          0                                0
    GX-150 MRT,05       1000                             1000
    GX-220 MRT,05          0                                0
    GX-150 APR,05       1000                             1000
    GX-220 APR,05          0                                0
    GX-150 MEI,05       1000                             1000
    GX-220 MEI,05          0                                0
    GX-150 JUN,05       1000                             1000
    GX-220 JUN,05          0                                0
    GX-150 JUL,05       1000                             1000
    GX-220 JUL,05          0                                0
    GX-150 AUG,05       1000                             1000
    GX-220 AUG,05          0                                0
    GX-150 SEP,05       1000                             1000
    GX-220 SEP,05          0                                0
    GX-150 OKT,05       1000      18655      12300       7355
    GX-220 OKT,05          0      20500      18245       2255
    GX-150 NOV,05       7355       1000       5355       3000
    GX-220 NOV,05       2255       1000       1255       2000
    GX-150 DEC,05       3000                             3000
    GX-220 DEC,05       2000                             2000
    24 rijen zijn geselecteerd.Regards,
    Rob.

  • SQL HELP NEEDED IN QUERY FOR COUNT

    I Have this Query
    SUM (CASE WHEN b.VET_OTHR_ELIG_CDE IN ('02', '03', '04') THEN 1 END) AS VET_YES,
    SUM (CASE WHEN b.VET_OTHR_ELIG_CDE = '01' THEN 1 END) VET_NO, COUNT (E.ACTV_CDE) AS CNT_ACTV_CDE
    Now i need to Add two more columns from the same Query Showing the count of VET_YES and VET_NO i.e count of TOTAL Veterans And TOTAL Non Veterans
    those two columns i will be using as summary columns in my report.The bolded columns are those which i need to show the total column .anyone please help in this issue ..
    ACTV_DESC ACTV_CDE VET_YES VET_NO CNT_ACTV_CDE
    INACT DUE 13993 2 1 3
    NOW I NEED TO MAKE IT LIKE THIS
    ACTV_DESC ACTV_CDE VET_YES VET_NO CNT_VET CNT_NONVET CNT_ACTV_CDE (This is the total count)
    INACT DUE 13993 2 1 2 1 3
    Thanks in Advance,
    Dev Kishore.T
    Message was edited by:
    Dev Kishore
    Message was edited by:
    Dev Kishore

    Check this link.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14223/aggreg.htm#sthref1612
    Regards
    Raj

  • Grouping Rules in PL/SQL Help needed

    Hi I have a requirement where I wan to group based on the below scenario
    I have a Table_A
    Table_A strcuture:
    create table table_a
    code number,
    name varchar2 (100),
    city varchar2 (100),
    dept varchar2 (100));;
    insert into table_a
    values
    1,'ABC','EA','A');
    insert into table_a
    values
    1,'ABC','EA1','A');
    insert into table_a
    values
    2,'BCD','EA2','A');
    insert into table_a
    values
    2,'ABC','EA3','A'');
    insert into table_a
    values
    3,'KBC','EA,'A');
    insert into table_a
    values
    3,'ABC','EA,'A');
    wan to group the above table data based on name,city,dept
    I wan the data  as
    1           ABC             EA1    A
                 BCD            EA2     A
    2           BCD            EA2     A
                 ABC            EA3     A
    3           KBC            EA      A
                 BCD            EA      A
    Kindly any help will be needful for me

    This is more of a presentation layer problem I would not handle it in SQL. For example if the presentation layer is SQL Plus you can use BREAK command, like this.
    SQL> select * from table_a;
          CODE NAME       CITY       DEPT
             1 ABC        EA         A
             1 ABC        EA1        A
             2 BCD        EA2        A
             2 ABC        EA3        A
             3 KBC        EA         A
             3 ABC        EA         A
    6 rows selected.
    SQL> break on code
    SQL>
    SQL> select * from table_a order by code;
          CODE NAME       CITY       DEPT
             1 ABC        EA         A
               ABC        EA1        A
             2 BCD        EA2        A
               ABC        EA3        A
             3 KBC        EA         A
               ABC        EA         A
    6 rows selected.
    But if you still wish to do it in SQL the right way is to use ROW_NUMBER like this.
    SQL> clear breaks
    breaks cleared
    SQL>
    SQL> select * from table_a;
          CODE NAME       CITY       DEPT
             1 ABC        EA         A
             1 ABC        EA1        A
             2 BCD        EA2        A
             2 ABC        EA3        A
             3 KBC        EA         A
             3 ABC        EA         A
    6 rows selected.
    SQL> select decode(rno, 1, code) code
      2       , name
      3       , city
      4       , dept
      5    from (
      6           select row_number() over(partition by code order by name) rno
      7                , t.*
      8             from table_a t
      9         )
    10  /
          CODE NAME       CITY       DEPT
             1 ABC        EA         A
               ABC        EA1        A
             2 ABC        EA3        A
               BCD        EA2        A
             3 ABC        EA         A
               KBC        EA         A
    6 rows selected.

  • Help needed to merge values from two tables -

    We have these three test tables shown, which have a common ID; And amount fields; I want the -------
    test1.val = test2.val + test3.val
    when they have common ids in them;
    I have shown the test data below: And the expected output;
    NOTE: In database with real table values - each of them have millions of rows in them. So effeciency is very important here;
    SQL> desc test1;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> desc test2;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> desc test3;
    Name Null? Type
    ID NUMBER
    VAL NUMBER
    SQL> select * from test1;
    ID VAL
    1 50
    2 50
    3 55
    4 60
    5 20
    5 rows selected.
    SQL> select * from test2;
    ID VAL
    1 25
    1 25
    2 5
    2 5
    4 75
    5 rows selected.
    SQL> select * from test3;
    ID VAL
    1 25
    1 25
    2 5
    2 25
    2 25
    5 10
    6 rows selected.
    I EXPECT the output to be:
    SQL> select * from test1;
    ID VAL
    1 100
    2 65
    3 20
    4 75
    3 20
    5 10
    6 rows selected.

    Need help with the update queries - joining three tables -

  • Help needed about character counting

    I need to count the characters in a file and I can do it
    though I need to specify which letter is the most significant,
    I couldn't find a good way of programming it,
    can anybody help?
    Thank you

    I hope it makes sense and I hope you can helpSure. Have a look at the following little class:public class CharCount implements Comparable {
       private char chr; // the character itself
       private int freq; // the number of times it occurred
       public CharCount(char chr) { this.chr= chr; }
       public char getChar() { return char; }
       public void inc() { freq++; }
       public boolean equals(Object obj) { return compareTo(obj) == 0; }
       public int hashCode() { return char+freq; }
       public int compareTo(Object obj) {
          CharCount that= (CharCount)obj;
          if (this.freq < that.freq) return -1;
          if (this.freq > that.freq) return  1;
          return this.chr-that.chr;
       public String toString() { return ""+chr; }
    }... most of this class is just the obligatory hullabaloo except for the
    compareTo method: if 'a' occurs more often than 'b', 'a' is considered
    larger. if both frequencies are equal it considers 'b' larger than 'a'
    lexicographically.
    Next we implement a map that uses a Character as its key and
    a CharCount as the associated value. This class can count all
    characters being fed to it:public class CharConsumer {
       private Map map= new HashMap();
       public void feed(char chr) {
          Character key= new Character(chr);
          CharCount cc= map.get(key);
          if (cc == null)
             map.put(key, cc= new CharCount(chr));
          cc.inc();
       public SortedSet getCharacters() {
          return new TreeSet(map.values());
    }... this class just updates the map when it receives another character.
    The trickery-dickery can be found in the last method which can all be
    explained if you read the corresponding API documentation.
    kind regards,
    Jos

  • Sql help needed

    sql gurus
    Oracle 11.2.0.2
    OS : AIX
    Requirement: I have a sql which generates rows between 100 and 150 daily. Changes depending on the dml.
    I need to generate 3 reports
    Report 1
    ex :
    if total rows =120
    1st report contain starting from row 1 upto row (total div 3)
    Row 1 to Row 40
    Report 2
    Row (total div 3) +1 to (total div 3) *2
    Report
    Row ((total div 3) *2) + 1 to Total rows.
    Currently the process of identifying this manual
    apart from using plsql
    Is it possible to do thru sql to get this done
    pl. let me know.
    I hope I have explained the problem clearly

    Hi,
    gl**** wrote:
    ... I hope I have explained the problem clearlyNo matter how clearly you explain a problem, you still ought to post CREATE TABLE and INSERT statements for some sample data, and the results you want from that data, as Hoek said. Explain how you get the results you want from that data. For example, you talk about getting rows 1 through (N/3), but you haven't said what determines the order of the rows. (In the query below, I assume it's a column called column_1.)
    Simplify the problem when you can. For example, instead of having 100 to 150 rows, post a problem that involves 6 to 8 rows.
    One way to do this in pure SQL is to use the NTILE function to divide the results evenly (as evenly as possible) into 3 groups, and only display one of the groups at a time, like this:
    WITH   got_third     AS
         SELECT     x.*
         ,     NTILE (3) OVER (ORDER BY  column_1)     AS third
         FROM     table_x  x
         WHERE     ...      -- If you need any filtering, put it here
    SELECT     *     -- Or list all columns except third
    FROM     got_third
    WHERE     third     = :third_wanted
    ;It would be more efficient if you generated all of the results at once, and then divided the output file into 3 parts, but an inefficient solution might be acceptable in this case.

  • XML SQL help needed

    I am having trouble using OracleXML getXML, after
    setting all the path variables in env.csh I try
    java OracleXML getXML -user "user/passwd" "select a, b from blog"
    but get the following error.
    ORA-01019: unable to allocate memory in the user side
    The same error occurs for jdk1.1.7 and jdk1.2
    null

    Hi Dean,
    It might be something to do with connecting through oci8 to the
    Oracle executable. ( I am not sure since I dont know ur
    configuration etc..). BTW what release of Oracle is this?
    One thing for you to try out would be to write a small java
    program against the OracleXMLQuery class to see if that works.
    I have attached a very simple program below:-
    import java.sql.*;
    import java.math.*;
    import oracle.xml.sql.query.*;
    import oracle.jdbc.*;
    import oracle.jdbc.driver.*;
    public class testXML{
    public static void main(String args[]) throws SQLException
    DriverManager.registerDriver
    (new oracle.jdbc.driver.OracleDriver());
    Connection conn = (Connection)
    DriverManager.getConnection("jdbc:oracle:oci8:scott/tiger@");
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery("select * from emp");
    OracleXMLQuery qry = new OracleXMLQuery(conn,rset);
    String xmlString = qry.getXMLString();
    System.out.println(" OUPUT IS "+xmlString);
    This code does a select from emp table available in scott/tiger
    schema. U can change the login and the table names
    appropriately. SEtup all the environment variables etc.. (see
    release notes), save this as testXML.java, run javac to get the
    class and execute it using "java testXML". If this doesnt work,
    try changing the getConnection line to use the thin jdbc, such
    as,
    DriverManager.getConnection
    ("jdbc:oracle:thin:@","scott","tiger");
    You can check out the JDBC documentation for how to specify
    your connection for your particular setup (such as specifying
    the port number etc.. if needed).
    Lemme know if it works,
    Murali
    Dean Kuo (guest) wrote:
    : I am having trouble using OracleXML getXML, after
    : setting all the path variables in env.csh I try
    : java OracleXML getXML -user "user/passwd" "select a, b from
    blog"
    : but get the following error.
    : ORA-01019: unable to allocate memory in the user side
    : The same error occurs for jdk1.1.7 and jdk1.2
    null

  • SQL Help -- Need help with pivoting the columns to rows

    I have a requierement to split the columns into multiple rows. For example:
    EMP_DEPT
    rowid empid1 ename1 dept1 empid2 ename2 dep2 empid2 ename2      dep3 empid4 ename4 dept4
    100001 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     10 4 SMITH 20
    100002 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     20      
    Note: EMP_DEPT may not always have all the 4 employee info populated for example in row 2 only 3 employees info is there
    I need to convert it and insert into EMPLOYEE table as follows:
    EMPLOYEE
    empid ename dept
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 10
    4 SMITH 20
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 20
    Thanks
    Kev

    Frank Thank You for your response.
    I am on oracle 10gR2.
    Posting some sample DDL and data here as requested:
    CREATE TABLE EMP
      PK          NUMBER(10),
      EMP_NAME1   VARCHAR2(100 BYTE),
      EMP_ID1     NUMBER(10),
      EMP_NAME2   VARCHAR2(100 BYTE),
      EMP_ID2     NUMBER(10),
      DEPT_NAME1  VARCHAR2(200 BYTE),
      DEPT_ID1    NUMBER(10),
      DEPT_NAME2  VARCHAR2(200 BYTE),
      DEPT_ID2    NUMBER(10)
    CREATE TABLE EMP_DEPT
    ( PK NUMBER(10),
    ENTY_TYPE VARCHAR2(100),
    ENTY_NAME VARCHAR2(100),
    ENTY_ID NUMBER(10)
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1, DEPT_NAME2, DEPT_ID2)
    Values
       (1, 'SCOTT', 10001, 'FRANK', 10002,
        'MARKETING', 10, 'ACCOUNTING', 20);
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1)
    Values
       (2, 'SCOTT1', 10003, 'FRANK1', 10004,
        'MARKETING1', 30);
    COMMIT;
    SELECT
    FROM
    EMP;
    PK     EMP_NAME1     EMP_ID1     EMP_NAME2     EMP_ID2          DEPT_NAME1     DEPT_ID1     DEPT_NAME2     DEPT_ID2
    1     SCOTT          10001     FRANK          10002          MARKETING     10          ACCOUNTING     20
    2     SCOTT1          10003     FRANK1          10004          MARKETING1     30               My requirement is to:
    SELECT from emp and INSERT INTO EMP_DEPT so that columns are broken into rows as follows
    PK ENTY_TYPE, ENTY_NAME    ENTY_ID
    1  EMPLOYEE   SCOTT        10001
    2  EMPLOYEE   FRANK        10002
    3  DEPARTMENT MARKETING    10
    4  DEPARTMENT ACCOUNTING   20    
    5  EMPLOYEE   SCOTT1       10003
    6  EMPLOYEE   FRANK1       10004
    7  DEPARTMENT MARKETING1   30          Thanks
    Kevin
    Edited by: user10210466 on Dec 8, 2010 1:37 PM

Maybe you are looking for