Need help in SQL Query: Update a row in a table & insert the same row into another table

I want to update a row in a table say Table A and the updated row should be inserted into another table say Table B. I need to do it in a single SQL query and i don't want to do it in PL/SQL with triggers. And i tried with MERGE statement but its working with this scenario. (Note: I'm using Oracle Database 10g Enterprise Edition Release 10.2.0.1.0).
Thanks in Advance.

Using Sven's code as an example, you could save the updated row in a sql plus variable. (also untested):
SQL> var v_id number
update tableA  
set colB='ABC' 
where colC='XYZ' 
returning id into :v_id;
insert into table A_History (ID, colA, colB, ColC)  
select id, ColA, ColB, ColC  
from tableA  
where id = :v_id;   

Similar Messages

  • Need help with SQL Query with Inline View + Group by

    Hello Gurus,
    I would really appreciate your time and effort regarding this query. I have the following data set.
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*20.00*-------------19
    1234567----------11223--------------7/5/2008-----------Adjustment for bad quality---------44345563------------------A-----------------10.00------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765--------------------I---------------------30.00-------------19
    Please Ignore '----', added it for clarity
    I am trying to write a query to aggregate paid_amount based on Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number and display description with Invoice_type 'I' when there are multiple records with the same Reference_No, Check_Number, Payment_Date, Invoice_Number, Invoice_Type, Vendor_Number. When there are no multiple records I want to display the respective Description.
    The query should return the following data set
    Reference_No---Check_Number---Check_Date--------Description-------------------------------Invoice_Number----------Invoice_Type---Paid_Amount-----Vendor_Number
    1234567----------11223-------------- 7/5/2008----------paid for cleaning----------------------44345563------------------I-----------------*10.00*------------19
    7654321----------11223--------------7/5/2008-----------Adjustment from last billing cycle-----23543556-------------------A--------------------50.00--------------19
    4653456----------11223--------------7/5/2008-----------paid for cleaning------------------------35654765-------------------I---------------------30.00--------------19
    The following is my query. I am kind of lost.
    select B.Description, A.sequence_id,A.check_date, A.check_number, A.invoice_number, A.amount, A.vendor_number
    from (
    select sequence_id,check_date, check_number, invoice_number, sum(paid_amount) amount, vendor_number
    from INVOICE
    group by sequence_id,check_date, check_number, invoice_number, vendor_number
    ) A, INVOICE B
    where A.sequence_id = B.sequence_id
    Thanks,
    Nick

    It looks like it is a duplicate thread - correct me if i'm wrong in this case ->
    Need help with SQL Query with Inline View + Group by
    Regards.
    Satyaki De.

  • [solved] inserting the same rows again into that table

    i have a table with some rows now i want to insert the same rows again into that table
    please tell me how to do it?
    not using export please only sql query please
    Message was edited by:
    littlemaster

    i m expecting that u commented on me (may be i m wrong). Only once, which we had already dealt with further up. My comment was continuing along another 'off topic' re: code graffitti. Sorry I you felt I was continuing to get at you.
    (If you look at the 'In Response to' part of ant post you can see which post any p[ost is intended to reply to)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Data from two tables in the same row in XML transformation

    Hi,
        I am using XML transformation for generating excel file which is to besent as email attachment.
        Here  I want to display the data from two internal tables in the same row in the excel. .I am using   <tt:loop ref=".<table name>"> ...  </tt:loop> for looping through the table. Can I loop two table simultaneously ? In that case how will I specify the fields in each table . Some of the fields in two tables are of same name and type.
    Please help...
    Thanks,
    Jissa

    Hello Brian,
    Thank you for your answer. It is approach I will use, I think. However let me ask: Would it be possible to have a Version in this layout, too? I mean to see, which value comes from Version A and which comes from Version B? Something like this:
    Calendar Month Version Sales Amount
    2011.01  B  200
    2011.02  B  300
    2011.03  A  260
    2011.04  A  230
    2011.05  A  200
    A

  • Deleting rows from one table while filter condition lies into another table

    Hi All,
    I'm facing a problem deleting a row from a table where the condition lies in other table. To ealaborate the scenario further let's say I have two table T1 (transaction table) and T2 (Master Table). I want to delete a record from table T1 by checking some conditions lies in table T2.
    I tried with the below query but this query deleting records from both the table.
    DELETE FROM ( SELECT * FROM T1 top INNER JOIN T2 tp
    ON top.TID = tp.TID
    WHERE top.DEAL_SITE_ID = inputparameter1
    AND (TP.SEGMENT <>inputparameter2 OR tp.segment is not null));
    Here the record is getting deleted from both the tables but I don't want to delete data from my master table i.e table T2.
    Any help would be highly appreciated. Thanks in advance.
    Regards,
    Subhadeep

    SQL> select *
      2   from the_table;
    X          Y
    AA         a
    BB         a
    CC         a
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a
    SQL>  delete from
      2  (
      3  select *
      4  from the_table  t1 inner join the_table_2 t2
      5  on  t1.x = t2.x
      6  and t1.y = t2.y);
    3 rows deleted.
    SQL> select *
      2   from the_table;
    X          Y
    AA         b
    DD         b
    SQL> select *
      2   from the_table_2;
    X          Y
    AA         a
    BB         a
    CC         a

  • Question about how not to insert the same row twice

    hello everyone
    i have two tables
    table employee_list
    employee_id
    employee_name
    employee_num
    employee_date
    and table employee_form
    employee_id
    employee_name
    employee_num
    employee_date
    table employee_form should contain the exact data like employee_list .
    if there are missing data i'm inserting it to table employee_form_miss(missing).
    now i have a probelm cause the compair between the two table,take place
    more then just one time.now if there are still missing data i don't want that to table employee_form_miss will insert the same data that already exist in this table.
    i've been thinking about constraints table employee_form_miss(employee_id
    employee_name
    employee_num
    employee_date).
    but i think it will be a wird way to handle this because i will do an insert
    and then what rollback? or delete?
    please help me how to manage this
    thanks in advance.

    hello everyone
    i have two tables
    table employee_list
    employee_id
    employee_name
    employee_num
    employee_date
    and table employee_form
    employee_id
    employee_name
    employee_num
    employee_date
    i'm using an embedded sql in cobol program
    DECLARE AA CURSOR FOR
    select a.employee_name ,a.employee_num,a.employee_date
    from employee_list a
    WHERE a.employee_date = :employee-date
    and NOT EXISTS
    (select null from employee_form
    WHERE employee_name =a.employee_name and
    employee_num = a.employee_num and
    employee_date = a.employee_date )
    i'm doing open and fetch to the cursor.
    and loop over the sqlerrd(3) result in order to insert them to the employee_form_miss table
    insert into employee_form_miss (employee_name,employee_num,employee_date)
    values (:employee-name,:employee-num,:employee-date)
    the employee_id in table employee_form_miss there is a trigger which
    Increment the sequence by 1 for each row that we insert.
    so my question was that if i'm doing a constraint, so still i have to do
    an insert and then if there is a constraint to do rollback or delete
    from duplicate row. is there a better way to manage this ?
    thank you

  • Need Help in SQL Query

    Hi all,
    I have data in the following manner:
    CASE_NUMBER HOURS FLAG
    1000 10 0
    1000 20 0
    1000 30 1
    1000 40 0
    1000 50 1
    Here I need to Calculate the total hours for a Case_number till i see the flag as 1.
    Here the result must be 10+20+30 Hrs
    Another Example
    CASE_NUMBER HOURS FLAG
    2000 10 1
    2000 20 1
    Here the result must be only 10.
    I am struggling to write a SQL query for this.
    Anyones help will be very much greatful
    Thanks in Advance
    Regards,
    Sengathir Subbarayan

    Look up analytical functions.
    something like sum(hours) OVER (PARTITION BY case_number ORDER BY something)
    will give you the sum for all rows.
    Then you probably want to "throw away" those rows after the flag maybe by summing the flag column too, and throw away all those where the flag is greater than 1 and where it is equal to 1 except for the first one.
    I suspect you actually have some other column (other than the number of hours) that define your order - that's what you put in the ORDER BY.
    Jon

  • Need help qith sql query

    I have a table with Columns as as below
    id number primary key
    object_name varchar2(100)
    object_value varchar2(100)
    Data is stored as follows
    id object_name object_value
    10 prop_num 436
    20 city dallas
    40 Misc 1 90
    50 Misc 1 desc min amount
    60 Misc 2 700
    70 Misc 2 desc interest amount
    80 Misc 3
    80 Misc 3 desc
    SQL should return result as shown below
    id object_name object_value
    10 prop_num 436
    20 city dallas
    40 min amount 90
    50 interest amount 700
    I have done this through plsql code by creating temp table. But I need to do it in a sql query. I am stuck here
    Any pointers/help is appreciated
    Thanks
    Edited by: user9327712 on Mar 11, 2010 8:14 AM

    I have a table where the ids are stored.
    *"object name"* column values are actually another table columns stored as rows here. So in our example prop_num, city,Misc 1, Misc 1 desc, Misc 2, Misc 2
    desc,Misc 3 , Misc 3 desc are all columns. These would not change any time
    The column object_value has values stored for respective columns.
    436, dallas , 90 , min amount , 700 , interest amount are all column values. So these can change.
    id object_name object_value
    10 prop_num 436
    20 city dallas
    40 Misc 1 90
    50 Misc 1 desc min amount
    60 Misc 2 700
    70 Misc 2 desc interest amount
    80 Misc 3
    90 Misc 3 desc
    Edited by: user9327712 on Mar 11, 2010 9:57 AM
    Edited by: user9327712 on Mar 11, 2010 10:00 AM
    Edited by: user9327712 on Mar 11, 2010 10:00 AM

  • Need help in SQL query to get only distinct records

    Hi all.
    I am new to oracle SQL and i want to write a query to get only distinct values from 2 tables.
    for example i hade 2 tables table1(employee_id,employee_no,grade) and another table2 with same structure.
    for example data in table1 is
    Employeeid employeeno Grade
    1 101 A
    1 101 B
    1 101 E
    1 101 D
    and data in table 2 is
    Employeeid employeeno Grade
    1 101 A
    1 101 B
    1 101 E
    i want to display only the fourth row like the data that doesnt exist in table2 i,e (1 101 D)
    I had too much records in both tables and i jst want to see the records that is in table 1 not in table 2 only.
    employeeid and employeeno are the same in both tables
    I hope u understand my query. I user left outer join and right outer join bt it displays all the results that and matching and unmatching. I want jst unmatched records.
    Any help is highly Appreciated.
    Thanx in Advance.
    I am using oracle 10G on windows

    Try MINUS:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/queries004.htm#i2054381
    SQL> -- generating sample data:
    SQL> with t1 as (
      2  select 1 employeeid, 101 employeeno, 'A' grade from dual union
      3  select 1, 101, 'B' from dual union
      4  select 1, 101, 'E' from dual union
      5  select 1, 101, 'D' from dual
      6  )
      7  ,  t2 as (
      8  select 1 employeeid, 101 employeeno, 'A' grade from dual union
      9  select 1, 101, 'B' from dual union
    10  select 1, 101, 'E' from dual
    11  )
    12  --
    13  -- actual query:
    14  --
    15  select employeeid
    16  ,      employeeno
    17  ,      grade
    18  from   t1
    19  minus
    20  select employeeid
    21  ,      employeeno
    22  ,      grade
    23  from   t2;
    EMPLOYEEID EMPLOYEENO G
             1        101 D
    1 row selected.

  • Complete novice needs help getting SQL Query into Crystal Reports XI

    Post Author: MissMarnie
    CA Forum: Data Connectivity and SQL
    So I was given an intro level web course and a monster reference guide in prep to format a report. One of our developers wrote me everything I need for the report into a SQL Query and now I'm supposed to format it in CR XII literally do not know what to do from here. I'm able to set up the correct server as a datasource, if that's useful, but I don't know how to make the querey into a bunch of formattable fields in  CR. If anyone can walk me through this, I'd be so grateful. I've attempted to look up SQL query in both the help and the book but I keep hitting a wall. The help dialog says things like "press this button" with no reference to what "this button" is. I'm sure it's obvious to the knowledgeable but I'm in a complete fog. Thanks in advance   

    Post Author: synapsevampire
    CA Forum: Data Connectivity and SQL
    IF you're trying to get assistance with setting up a query as the source for a report, try posting your Crystal version and the database type.
    Different software works differently.
    In CR 9 and above, under the connection to the database you'll see Add Command. Select that and you can paste the query in.
    As for not knowing how to generate a report, that requires experience, there's no generic solution of course..
    -k

  • Need help with SQL Query

    I am trying to build a query that sums up 12 columns depending on some accounting variables.
    example:
    SELECT gbmcu, gbco, gbfy,'',SUM(gban01 gban02 gban03 gban04 gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12) AS Oil_Volumes
    FROM PRODDTA.F0902
    WHERE GBCO = '00099'
    AND GBFY = 5
    AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
    GROUP BY gbmcu, gbco, gbfy
    The condition that changes is :AND GBLT = 'QU' AND GBOBJ = 5015 AND GBSUB = '105'
    I need to do this for 17 different conditions - I need to make the query as optimized as possible.
    I tried using a case statement but that takes forever (the table is over 4 million records to scan through).
    Please let me know if anyone has any suggestions on how to create something to perform these calculations.
    thanks,
    Pam

    I think I would tend to write that query as:
    SELECT gbmcu, gbco, gbfy,
           SUM(CASE WHEN gblt = 'QA' AND gbobj = 5015 AND gbsub = '105' THEN
                    gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Sales
           SUM(CASE WHEN gblt = 'QU' AND gbobj = 5015 AND gbsub = '105' THEN
                    gban01+gban02+gban03+gban04+gban05+gban06+gban07+gban08+gban09+gban10+gban11+gban12 END) Oil_Volumes
    FROM proddta.f0902
    WHERE gbco = '00099' and
          gbfy = 5 and
          gblt IN ('QA', 'QU') and
          gbpbj = 5015 and
          gbsub = '105'
    GROUP BY gbmcu, gbco, gbfySUM the CASE rather than CASE SUM. Also, as written, your query will look at all of the records in f0902 whether or not they meet one of the Case criteria, so I would put the required values in the WHERE clause as well. Your samples only show gblt changing, so you may need to make the gbpbj and gbsub predicates IN lists as well.
    If the query runs in 1.5 hours calculating one value, I would expect it to be about the same calculating 17 values, since I would bet that most of the run time is accessing the table rather than doing the math. It would almost certainly be faster than running essentially the same query 17 times.
    Indexes on some or all of the columns in the WHERE clause may help, depending on how selective the columns are. At a guess, I would suggest that gbco and gbfy would be good candidates.
    Finally, are you sure that gbsub is a character field? The only example we have is a number.
    HTH
    John

  • Need help with sql query dates

    Hi,
    I have a sql query where i need to extract some info between given dates. The where clause of this query is as follows:
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :P_DATE_FROM
    AND CPD_VOUCHER_DATE < (:P_DATE_TO+1)
    When i execute the query in toad, i can view the data but not the execution plan.It gives an error ORA-00932-Inconsistent Datatypes.
    But when i remove (+1) from :P_DATE_TO, i can c the execution plan and data. Will the data be different from the previous one.
    Please suggest how to rewrite the query.

    Can you please give it a try?
    WHERE CPD_BUS_UNIT=:ESI_PRM_1
    AND CPD_VOUCHER_DATE >= :to_date(P_DATE_FROM)
    AND CPD_VOUCHER_DATE < (to_date(:P_DATE_TO)+1) Regards

  • Need Help on Sql Query

    Hi,
    I have a client requirement to show a report on the device availability. The report should show the output as
    Node Availability%
    Formula for Availability = (Total No. of Failed/Total No. rows) * 100
    My Oracle Table has the following data
    NODE     SUMMARY
    172.16.10.55     Default Interface Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Interface Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Chassis Ping restore for 172.16.10.55
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Chassis Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.55     Default Interface Ping restore for 172.16.10.55
    172.16.10.55     Default Interface Ping fail for 172.16.10.55: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Interface Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Chassis Ping fail for 172.16.10.56: ICMP timeout
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Chassis Ping restore for 172.16.10.56
    172.16.10.56     Default Interface Ping fail for 172.16.10.56: ICMP timeout
    In the above table the Summary column has the details like 'Ping fail' , 'Ping restore' for each Node. So, for each Node I have to compute the Total Ping Fail / (Total Ping Fail + Ping Restore) * 100 to compute the availability %.
    My output should be like the below
    Node Availability%
    172.16.10.55 55.55
    172.16.10.56 54
    Can someone please help me with query.
    I appreciate your help in advance.
    Thanks.
    Regards,
    RaviShankar.

    My Oracle Table has the following dataThat's great, but if you want maximum response to your question, then post CREATE TABLE + INSERT INTO statements.
    I currently do not have the time to turn your data into them.
    And always post the database version you're using.
    http://tkyte.blogspot.com/2005/06/how-to-ask-questions.html
    Also use the {noformat}{noformat} tag in order to post examples that benefit from staying formatted and thus readable when posted on the forum.
    Simply put the tag before and after your examples.
    For example, when you type:
    {noformat}select *
    from dual;{noformat}
    it will appear as:select *
    from dual;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Need help writing sql query

    i am trying to write sql query for a single recordset.
    I have an items table with all the standard item info and an item_colorID.
    i have a color_lookup table with 2 columns, item_colorID and color_ID
    i have a colors table with 2 columns, color_ID and color
    i want to join the tables and filter it so that a repeat region shows dynamic data of item name, description, thumb, price
    and also a list/menu dynamically populated by color
    filtered so that each item shows in the list/menu only the colors that the item has available.
    i have tried different variations of this sql
    SELECT * FROM items INNER JOIN color_lookup ON color_lookup.item_colorID = items.item_colorID INNER JOIN colors ON colors.color_ID = color_lookup.color_ID WHERE items.itemCatID = 3 ORDER BY items.itemName
    but the list/menu shows every color choice multiplied by the number of items in that color
    ie  White will show 80+ times.
    thanks for your help,
    jim balthrop

    bregent,
    thanks for your help.
    I am building a shopping cart and i have a recordset to list the items and a repeat region for that recordset
    i have a second recordset for the colors joined to the item_colorID nested inside the repeat region.
    the shopping cart software has a 'lookup from recordset' choice for the add to cart servior behavior
    and then i bind to the columns on the cart page.
    it produces this code
    if (isset($totalRows_rs_itemscat3) && $totalRows_rs_itemscat3 > 0)    {
        $row_rs_itemscat3 = WAEC_findRecordMySQL($rs_itemscat3, "item_ID", $ATC_itemID);
        if ($row_rs_itemscat3)    {
          $ATC_itemName = "".$row_rs_itemscat3['itemName']  ."";// column binding
          $ATC_itemDescription = "".$row_rs_itemscat3['itemShortDesc']  ."";// column binding
          $ATC_itemWeight = floatval("".$row_rs_itemscat3['itemWeight']  ."");// column binding
          $ATC_itemQuantity = "".$_POST["Farrington_1_Quantity_Add"]  ."";// column binding
          $ATC_itemPrice = floatval("".$row_rs_itemscat3['itemPrice']  ."");// column binding
          $ATC_itemThumbnail = "".$row_rs_itemscat3['itemThumb']  ."";// column binding
          $ATC_itemcolorchoice = "".$row_rs_colors['color']  ."";// column binding
          mysql_data_seek($rs_itemscat3, 0);
          $row_rs_itemscat3 = mysql_fetch_assoc($rs_itemscat3);
    the column binding for the colors is from a different recordset and when redirecting to the cart page the color info will not show.
    So my thinking is if i could get the color list/menu to populate from the same recordset as the item listing, it would solve my add to cart server behavior.
    Is it possible to do this with only one recordset?
    the products page and the cart page can be seen
    http://www.farrington-enterprises.com/rain-gutters.php
    add an item to the cart with any color choice and the color info does not carry to the cart.

  • Need help regarding sql query

    hii All
    I need help for pl/sql function.
    I build a function for monthly attendance all employees.
    but now i want to show all Sundays with 'S' and others respectively 'P' and 'A'.
    Currently Sunday also shows 'A'
    So please help
    SQL queries ... like
    SELECT DISTINCT AL.USERNAME,
    CASE WHEN DAY1 =1 THEN 'P' ELSE 'A' END DAY1,
    CASE WHEN DAY2 =1 THEN 'P' ELSE 'A' END DAY2,
    CASE WHEN DAY3 =1 THEN 'P' ELSE 'A' END DAY3,
    CASE WHEN DAY31 =1 THEN 'P' ELSE 'A' END DAY31
    FROM
    SELECT DISTINCT USERNAME, SUM(CASE WHEN
    fromdt=TRUNC(L.LOGIN_DATE) THEN
    1
    ELSE
    0
    END) DAY1
    ,SUM(CASE WHEN
    fromdt +1=TRUNC(L.LOGIN_DATE) THEN
    1
    ELSE
    0
    END) DAY2,
    SUM(CASE WHEN
    fromdt+30=TRUNC(L.LOGIN_DATE) THEN
    1
    ELSE
    0
    END) DAY31
    FROM ( SELECT DISTINCT TRUNC(LOGIN_DATE)LOGIN_DATE ,USERNAME FROM FCDM_AUDIT_TRAIL_NEW WHERE
    TRUNC(LOGIN_DATE) BETWEEN fromdt AND todt
    -- to_date( login_date, 'dd-mom-yyyy') between to_date( fromdt, 'dd-mom-yyyy') and to_date( todt, 'dd-mom-yyyy')
    ) L
    GROUP BY USERNAME
    ) AL;
    how can i show matched Sundays and show with 'SUN' or 'S'
    Regards
    vij..

    Try this way:
    SELECT USERNAME,
           MAX(CASE WHEN to_char(fromdt,'d')='1' and fromdt=TRUNC(L.LOGIN_DATE) THEN 'S'
                    WHEN to_char(fromdt,'d')!='1' and fromdt=TRUNC(L.LOGIN_DATE) THEN 'P'
                    ELSE 'A') DAY1,
           MAX(CASE WHEN to_char(fromdt+1,'d')='1' and fromdt+1=TRUNC(L.LOGIN_DATE) THEN 'S'
                    WHEN to_char(fromdt+1,'d')!='1' and fromdt+1=TRUNC(L.LOGIN_DATE) THEN 'P'
                    ELSE 'A') DAY2,
           MAX(CASE WHEN to_char(fromdt+30,'d')='1' and fromdt+30=TRUNC(L.LOGIN_DATE) THEN 'S'
                    WHEN to_char(fromdt+30,'d')!='1' and fromdt+30=TRUNC(L.LOGIN_DATE) THEN 'P'
                    ELSE 'A') DAY31
    FROM
    (SELECT DISTINCT TRUNC(LOGIN_DATE) LOGIN_DATE,
            USERNAME
       FROM FCDM_AUDIT_TRAIL_NEW
      WHERE TRUNC(LOGIN_DATE) BETWEEN fromdt AND todt
    ) L
    Group by USERNAME
    ;Max
    http://oracleitalia.wordpress.com

Maybe you are looking for