Compare two rows in a same table

Dear all
I need to compare two rows in the same table, I dont know hoe to do it in pl/sql. Some one please help me on this.
example:
tr br price
xya0001 ama7 12
xya0003 ama6 14
xya0004 ama7 16
in the table tr is a unique value for each row, I need to compare price column and see whether the first value is less or greater than the next value and, if it is greater put the corresponding br value to a variable and if it is smaller put the corresponding br value to another variable. I dont know a method to do it, as I'm new to pl/sql. Some one please help me in this

not sure what you intend to do as you have mentioned that "TR" is unique and you just want to compare each record with just the next record. Hope below query helps. The value "G" or "L" in flag would indicate if the current records price is greater than or less than the price in next record.
select tr,br,price,col4, case when price> col4 then 'G'  when price< col4 then 'L' end flag from (
select tr,br,price,lag(price,1,0) over(order by tr) col4 from testcomp
)

Similar Messages

  • SUM two ROWS in the SAME Table

    Hi,
    I have a problem with this issue. I want to sum two rows from the same table, but I don´t know how to do that. I tried to do it with CTE, but always I get the same error "Ambiguous". I would like to ask you, if there is other manner to get that
    data (sum two rows) and if it is possible to see examples about it.
    Thank you  in advance

    Hi Vaibhav,
     I leave you my scrip:
    USE Modelling
    GO
    --TABLE Aer_Lingus_Income_Statement
    IF OBJECT_ID('Aer_Lingus_Income_Statement') IS NOT NULL
    DROP TABLE Aer_Lingus_Income_Statement
    GO
    CREATE TABLE Aer_Lingus_Income_Statement
    ID [nvarchar](255) NOT NULL,
    Name_Account [nvarchar](255) NULL,
    Company [nvarchar](255) NULL,
    Level0_Account [nvarchar](255) NULL,
    Level1_Account [nvarchar](255) NULL,
    Level2_Account [nvarchar](255) NULL,
    Level3_Account [nvarchar](255) NULL,
    Level4_Account [nvarchar](255) NULL,
    Level5_Account [nvarchar](255) NULL,
    Level6_Account [nvarchar](255) NULL,
    Level7_Account [nvarchar](255) NULL,
    Level8_Account [nvarchar](255) NULL,
    Year_2006 decimal (15,2) null,
    Year_2007 decimal (15,2) null,
    Year_2008 decimal (15,2) null,
    Year_2009 decimal (15,2) null,
    Year_2010 decimal (15,2) null,
    Year_2011 decimal (15,2) null,
    Year_2012 decimal (15,2) null,
    Year_2013 decimal (15,2) null,
    GO
    ALTER TABLE Aer_Lingus_Income_Statement
    ADD CONSTRAINT PK_Aer_Lingus_Income_Statement PRIMARY KEY (ID)
    GO
    INSERT INTO Aer_Lingus_Income_Statement
    SELECT *
    FROM Aer_Lingus_data_Income
    IF OBJECT_ID('Aer_Lingus_Income_Statement_Historic') IS NOT NULL
    DROP VIEW Aer_Lingus_Income_Statement_Historic
    GO
    CREATE VIEW Aer_Lingus_Income_Statement_Historic
    as
    Select Level0_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level0_Account ='Revenue'
    Group by Level0_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Passenger revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Ancillary revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Other revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account= 'Cargo revenue' and Level0_Account ='Revenue'
    Group by Name_Account
    UNION ALL
    Select Level0_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level0_Account ='Operating expenses'
    Group by Level0_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Staff costs' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Depreciation, amortisation and impairment' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Aircraft operating lease costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Fuel and oil costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Maintenance expenses' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Airport charges' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='En-route charges' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Distribution costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Ground operations, catering and other operating costs' and Level0_Account ='Operating expenses'
    Group by Name_Account
    UNION ALL
    Select Level1_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Level1_Account ='Other (gains)/losses - net' and Level0_Account ='Operating expenses'
    Group by Level1_Account
    UNION ALL
    Select Name_Account , sum(Year_2006) as Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    Where Name_Account ='Employee profit share' and Level0_Account ='Operating expenses'
    Group by Name_Account
    GO
    WITH sumasRevenue
    AS (
    SELECT Name_Account, ID
    , sum(Year_2006) AS Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    WHERE Level0_Account = 'Revenue'
    GROUP BY Name_Account, ID
    WITH ROLLUP
    , total
    AS (
    SELECT Y2006,Y2007 ,Y2008,Y2009 ,Y2010 ,Y2011 ,Y2012 ,Y2013
    FROM sumasRevenue
    WHERE Name_Account IS NULL
    sumasOperatingExpensive
    AS (
    SELECT Name_Account, ID
    , sum(Year_2006) AS Y2006, sum (Year_2007) as Y2007, sum (Year_2008) as Y2008, sum (Year_2009) as Y2009, sum (Year_2010) as Y2010,
    sum (Year_2011) as Y2011, sum (Year_2012) as Y2012, sum (Year_2013) as Y2013
    FROM Aer_Lingus_data_Income
    WHERE Level0_Account = 'Operating expenses'
    GROUP BY Name_Account, ID
    WITH ROLLUP
    , total1
    AS (
    SELECT Y2006,Y2007 ,Y2008,Y2009 ,Y2010 ,Y2011 ,Y2012 ,Y2013
    FROM sumasOperatingExpensive
    WHERE Name_Account IS NULL
    SELECT distinct ID , s.Name_Account,
    (s.Y2006* 1.0 - t.Y2006) AS [V2006] ,(s.Y2007* 1.0 -T.Y2007 ) as [V2007] , (s.Y2008* 1.0 /T.Y2008 ) as [V2008],(s.Y2009* 1.0 /T.Y2009 ) as [V2009],
    (s.Y2010* 1.0 /T.Y2010 ) as [V2010],(s.Y2011* 1.0 /T.Y2011 ) as [V2011],(s.Y2012* 1.0 /T.Y2012 ) as [V2012],(s.Y2013* 1.0 /T.Y2013 ) as [V2013]
    FROM sumasRevenue AS s , sumasOperatingExpensive AS t
    Where ID IS NOT NULL
    UNION ALL
    SELECT distinct ID,COALESCE(s.Name_Account,'NON CURRENT ASSETS') AS Name_Account ,
    sum (s.Y2006* 1.0 / t.Y2006) as V2006,sum (s.Y2007* 1.0 / t.Y2007) as V2007,sum (s.Y2008* 1.0/ t.Y2008) as V2008,sum (s.Y2009* 1.0/ t.Y2009) as V2009,sum (s.Y2010* 1.0/ t.Y2010) as V2010,
    sum (s.Y2011* 1.0 / t.Y2011) as V2011,sum (s.Y2012* 1.0/ t.Y2012) as V2012,sum (s.Y2013* 1.0/ t.Y2013) as V2013
    FROM sumasRevenue as s , sumasOperatingExpensive as t
    Where ID IS NULL and Name_Account IS NULL
    GROUP BY Name_Account, ID
    WITH ROLLUP
    select *
    from Aer_Lingus_Income_Statement_Historic
    Thank you in advance

  • Compare two results from the same table

    i have two results from the same table that i would like to compare. below is my query and the results i want to compare
    SELECT tblItemRoutingBOM.ItemRevID, tblItem.ItemID, tblItem.PartNum, tblItem.ItemName, tblItem.ManufacturerPartNum AS [Mfg Part#], tblItemRoutingBOM.Quantity
    FROM tblItemRouting
    INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
    INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
    WHERE tblItemRoutingBOM.ItemRevID in (61,70)
    as you can see i am returning two records using the where clause
    ItemRevID, ItemID, PartNum, ItemName, Manufacturer, Mfg Part#, Quantity
    61,121,331503,.233 Aluminum Sheet,,1
    70,121,331503,.233 Aluminum Sheet,,3
    now what i am looking for is to combine these two together into one row with the following added.  two columns for each QTY, QTY1 = 1 and QTY2 = 3 with a third column added that is the difference between the two QTY Diff = 2
    Any thoughts?

    Here are the two statements that i want to combine, results for each are attached
    SELECT tblItem.ItemID, Sum(tblItemRoutingBOM.Quantity) AS SumOfQuantity, tblItem.PartNum AS [Part #],
    tblItem.ItemName, tblManufacturer.ManufacturerName AS Manufacturer, tblItem.ManufacturerPartNum AS [Mfg Part#]
    FROM tblItemRouting
    INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
    INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
    INNER JOIN tblUnits ON tblItem.UnitID = tblUnits.UnitID
    LEFT JOIN tblManufacturer ON tblItem.ManufacturerID = tblManufacturer.ManufacturerID
    WHERE tblItemRoutingBOM.ItemRevID=61
    GROUP BY tblItem.ItemID,tblItem.PartNum,tblItem.ItemName,tblManufacturer.ManufacturerName,tblItem.ManufacturerPartNum
    SELECT tblItem.ItemID, Sum(tblItemRoutingBOM.Quantity) AS Quantity, tblItem.PartNum AS [Part #],
    tblItem.ItemName, tblManufacturer.ManufacturerName AS Manufacturer, tblItem.ManufacturerPartNum AS [Mfg Part#]
    FROM tblItemRouting
    INNER JOIN tblItemRoutingBOM ON tblItemRouting.ItemRoutingID = tblItemRoutingBOM.ItemRoutingID
    INNER JOIN tblItem ON tblItemRoutingBOM.ItemID = tblItem.ItemID
    INNER JOIN tblUnits ON tblItem.UnitID = tblUnits.UnitID
    LEFT JOIN tblManufacturer ON tblItem.ManufacturerID = tblManufacturer.ManufacturerID
    WHERE tblItemRoutingBOM.ItemRevID=70
    GROUP BY tblItem.ItemID,tblItem.PartNum,tblItem.ItemName,tblManufacturer.ManufacturerName,tblItem.ManufacturerPartNum
    114,11,55002,Pepsi Blue Cap,NULL,
    117,5,331501,Marigold Yellow For ABS,NULL,
    121,1,331503,.233 Aluminum Sheet,NULL,
    125,2,331504,Velvet Vinyl .008,NULL,
    114,33,55002,Pepsi Blue Cap,NULL,
    117,15,331501,Marigold Yellow For ABS,NULL,
    121,3,331503,.233 Aluminum Sheet,NULL,
    125,6,331504,Velvet Vinyl .008,NULL,
    my returned result should combine above with two extra columns (two extra columns because i have two results to combine)
    114, 11, 33, 22, 55002, Pepsi Blue Cap, NULL,
    117, 5, 15, 10, 331501, Marigold Yellow For ABS, NULL
    121,1, 3, 2, 331503, .233 Aluminum Sheet, NULL
    125, 2, 6, 4, 331504, Velvet Vinyl .008, NULL
    Columns go as such, ID, QTY1 (for 61), QTY2 (for 70), Diff (QTY1-QTY2), PartNum, ItemName, Mfg, Mfg Part#
    IF the results from one of those two are empty then i would see something like this
    114, 11, 0, 11, 55002, Pepsi Blue Cap, NULL,
    117, 5, 0, 5, 331501, Marigold Yellow For ABS, NULL
    121,1, 0, 1, 331503, .233 Aluminum Sheet, NULL
    125, 2, 0, 2, 331504, Velvet Vinyl .008, NULL

  • How to compare two fields from the same table in the select statement

    Hi, friends
    I try to compare tow fields from the same table, but no result,
    For example, this
    data: cptotchek tyep i.
    select count(*) into cptotchek
    from aufk where erdat = aufk-idat2 .
    The result is  cptotchek = 0, but there are the records in aufk , where,  aufk-erdat = aufk-idat2.
    Please, help me, i don't use the loop statement for optimize my program.
    Regards

    Hi  ,
           it will not return  any value   when you are using   column of same table 
           such as Date Field   , Because  while Using Aggregate Function  it will not check with self column
    .      For that you have to take data in one internal table and then you can work on it  .
         And if you are worried about Performance  it will not affect  , untill you are selecting only required data  .
    you can try this way  .
    data: cptotchek type i.
    types : begin of  w_aufk.
            include structure aufk  .
          types : end of  w_aufk .
    data : it_aufk type standard table of w_aufk with header line  .
    select * into corresponding fields of table it_aufk
    from aufk  .
    loop at it_aufk .
    if it_aufk-erdat  = it_aufk-idat2 .
    write : / it_aufk-erdat , it_aufk-idat2 .
    else .
    delete it_aufk .
    endif  .
    endloop.
    Regards
    Deepak.

  • Comparing two rows field by field through a loop

    Hi all,
    I've got a tricky issue:
    There are two tables (almost) identically designed;
    In the first one there are lets say some new data and in the 2nd one there is data to be hold & adjusted;
    I built up a third table, which contains the meta informations about the two other tables (i.e. it describes the tables, so for each field of these tables, there is the field name, field type, primary key marker, etc.);
    The challenge now is, how can I compare two rows (of the same primary key) field by field and get out the differences (and adjusting the target table row) using PL/SQL procedures/functions.
    I thought a create a cursor over the 3rd table and call functions to get the fields out (given by the field name of the cursor), compare the two fields and return if it's equal or different...
    As I've seen, there is now direct way to replace a field name in a statement - but how to resolve this with a cool workaround?
    In addition, there are about 120 pairs of such tables, to be compared in the same way - so I decided to prevent creating hard coded design for the software.
    Even the selection of a pair of rows from the two tables should be parameterized, 'cause the primary keys are of course different in the 120 table pairs.
    Any hints or suggestions?
    Thanks in advance & regards,
    Peter

    Hi Peter,
    I am very far from being an expert in Oracle but, everything I've read so far strongly suggests that PL/SQL is often the fastest among the customized solutions (beating even compiled C code). The reason - from what I've understood - is that PL/SQL is part of the Oracle kernel/engine, other languages simply aren't.
    I suggest you do your own research to confirm what I've just said above.
    On a completely different note, when I first read your post, I started writing a reply and decided to discard it because, I figured you probably would find it too far off your original thoughts. However, then you wrote:
    >
    There are some reasons to prevent hard coding, but it may be possible to generate the PL/SQL-code for each pair of tables by an external program.
    >
    This is exactly what I was mentioning in the post I ended up discarding. The basic step by step process I was going to mention is as follows:
    STEP 1: If possible, write one PL/SQL program that does the job properly for one set of tables. Test it thoroughly and identify potential differences in the process if it had to be applied against other tables. Make it as generic as reasonably possible, that is, keeping the code as simple as possible.
    STEP 2: turn the working code of step 1 into a template (usually replacing table names, columns, etc by some token that would not be a valid name).
    STEP 3: generate a list of the tables and their corresponding columns you need to process. This list may need to be massaged a little to become the generating seed of 120 programs (or so based on what you've said).
    STEP 4: if you don't know Perl or AWK then (don't be alarmed...) download AWK (not Perl) and learn it... you can learn the thing in a couple days (maybe even less). It is a very simple and straightforward text processing language, I know non progammers that learned enough in one day to do useful things with it. Using AWK you can easily generate the 120 programs you need from a working template in very little time (a few hours after you've become proficient). By the way, there is AWK, GAWK, NAWK, all pretty much the same thing and all free. The standard manual for AWK is the one written by the authors Aho, Weinberger and Kernigan, about 100 small pages, it's an easy read and no programmer should be without it :) (better than American Express!)
    What you've described sounds just like the thing to use AWK for. I once used AWK to generate 27,000 (that's 27 thousand) lines of COBOL code, debugged and fully tested in 2 days! (testing was automated using AWK too!) It would have taken much longer to just type all that code.
    Anyway, I hope that gives you something to think about and be of some help.
    John.

  • Compare two rows in same table

    Hi,
    I want to compare two rows (some columns) in the same table, and if the data in the data columns is different, I want to pick the latest one. The table is date tracked. For instance I have an address table with different addresses for an employee with effective date. I want to be able to pick the latest row if the postal code is different for the 2 rows. Is this possible in sql. I can do this in Pl/sql, but dont want to use it. Eg
    address_id, postal_code, person_id,last_update_date
    123, pn123,1,12-JAN-01
    124,pu124,1,13-JAN-01
    I want to be able to retrieve just the second line.
    Any help is appreciated

    Welcome to the forum!
    Whenever you post please provide your 4 digit Oracle version (result of SELECT * FROM V$VERSION).
    >
    The table is date tracked. For instance I have an address table with different addresses for an employee with effective date. I want to be able to pick the latest row if the postal code is different for the 2 rows.
    >
    Your question is a little confusing because you are using terms like 'date tracked' and 'effective date' without explaining exactly what your definitions of those terms is.
    Why do you want the latest record ONLY if the postal code is different? What if the address is different? Then which record do you want?
    Why not just take the record for each person/company that has the latest date? If the data is the same then it doesn't which record you get so the one with the latest date will do. And if the data is different taking the one with the latest date gives you the latest data.
    The classic definition of effective date is 'the date the information becomes effective'. Information with a given effective date is NOT in effect before that date and is SUPERCEDED when data is entered with a later effective date if the actual date is later than or equal to the effective date. Using your data
    >
    123, pn123,1,12-JAN-01
    124,pu124,1,13-JAN-01
    >
    The first record IS NOT effective for dates prior to 12-JAN-01. In fact for a query looking for data prior to that date there isn't any data.
    The first record is also NOT effective for dates on or after 13-JAN-01. Only the second record is effective.
    If you added a record for 14-JAN-01 this record would not be effective until on or after that date (i.e. not for another 4 1/2 months).
    So for the classic definition of effective date the query needs to provide the AS OF date to use to obtain the data. If, as in your system, you are not allowed to create records with dates in the future and you just want the latest record then you can just select the record with the MAX(myDate) value for the given person_id, address_id or whatever your key values are.
    Edited by: rp0428 on Aug 11, 2012 7:50 AM

  • SUM two fileds from different rows from the same table

    I would like to SUM two fileds from different rows from the same table but I don't know how to do that.
    E.g.
    BillingTransactionsIndex      CreateDate      UserType      UserIndex      TransType      Reference      Total      Balance
    2      6/5/2008 15:02      1      51      1      150      -288.2      -288.2
    5      6/8/2008 11:55      1      51      1      157      -1.58674      -289.787
    In the table above I want SUM fields Total and Balance for the first row and the the next row SUM 2nd row Total with 1st row Balance
    Please help
    Thanks

    SQL> with tbl as
      2  (select 1 as ID,  90 as total from dual
      3          union all
      4  select 2 as ID,  23 as total  from dual
      5          union all
      6  select 3 as ID,  15 as total  from dual
      7          union all
      8  select 4 as ID,  20 as total  from dual)
      9  select id , total, sum(total) over (order by ID) as balance from tbl
    10  /
            ID      TOTAL    BALANCE
             1         90         90
             2         23        113
             3         15        128
             4         20        148
    SQL>

  • How to compare two rows from two table with different data

    how to compare two rows from two table with different data
    e.g.
    Table 1
    ID   DESC
    1     aaa
    2     bbb
    3     ccc
    Table 2
    ID   DESC
    1     aaa
    2     xxx
    3     ccc
    Result
    2

    Create
    table tab1(ID
    int ,DE char(10))
    Create
    table tab2(ID
    int ,DE char(10))
    Insert
    into tab1 Values
    (1,'aaa')
    Insert
    into tab1  Values
    (2,'bbb')
    Insert
    into tab1 Values(3,'ccc')
    Insert
    into tab1 Values(4,'dfe')
    Insert
    into tab2 Values
    (1,'aaa')
    Insert
    into tab2  Values
    (2,'xx')
    Insert
    into tab2 Values(3,'ccc')
    Insert
    into tab2 Values(6,'wdr')
    SELECT 
    tab1.ID,tab2.ID
    As T2 from tab1
    FULL
    join tab2 on tab1.ID
    = tab2.ID  
    WHERE
    BINARY_CHECKSUM(tab1.ID,tab1.DE)
    <> BINARY_CHECKSUM(tab2.ID,tab2.DE)
    OR tab1.ID
    IS NULL
    OR 
    tab2.ID IS
    NULL
    ID column considered as a primary Key
    Apart from different record,Above query populate missing record in both tables.
    Result Set
    ID ID 
    2  2
    4 NULL
    NULL 6
    ganeshk

  • How to compare two rows in PL/SQL?

    Hi All,
    How to compare two rows in PL/SQL? Is there any method that I can use instead of comparing them column by column?
    Any feedback would be highly appreciated.

    PhoenixBai wrote:
    Hi All,
    How to compare two rows in PL/SQL? Is there any method that I can use instead of comparing them column by column?What "rows" are you referring to?
    If you're talking of rows within a PL/SQL associative array there are techniques as described in the documentation... e.g.
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    type v1 is table of number;
      3    r1 v1 := v1(1,2,4);
      4    r2 v1 := v1(1,2,3);
      5  begin
      6    if r1 MULTISET EXCEPT DISTINCT r2 = v1() then
      7      dbms_output.put_line('Same');
      8    else
      9      dbms_output.put_line('Different');
    10    end if;
    11* end;
    SQL> /
    Different
    PL/SQL procedure successfully completed.
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2    type v1 is table of number;
      3    r1 v1 := v1(1,2,3);
      4    r2 v1 := v1(1,2,3);
      5  begin
      6    if r1 MULTISET EXCEPT DISTINCT r2 = v1() then
      7      dbms_output.put_line('Same');
      8    else
      9      dbms_output.put_line('Different');
    10    end if;
    11* end;
    SQL> /
    Same
    PL/SQL procedure successfully completed.
    SQL>If you're talking about rows on a table then you can use the MINUS set operator to find the rows that differ between two sets of data...
    SQL> select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-1981 00:00:00       1600        300         30
          7521 WARD       SALESMAN        7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-1981 00:00:00       2975                    20
          7654 MARTIN     SALESMAN        7698 28-SEP-1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-1981 00:00:00       2850                    30
          7782 CLARK      MANAGER         7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17-NOV-1981 00:00:00       5000                    10
          7844 TURNER     SALESMAN        7698 08-SEP-1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-1987 00:00:00       1100                    20
          7900 JAMES      CLERK           7698 03-DEC-1981 00:00:00        950                    30
          7902 FORD       ANALYST         7566 03-DEC-1981 00:00:00       3000                    20
          7934 MILLER     CLERK           7782 23-JAN-1982 00:00:00       1300                    10
    14 rows selected.
    SQL> select * from emp2;
         EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
          7521 WARD       SALESMAN        7698 22-FEB-1981 00:00:00       1250        500         30
          7566 JONES      MANAGER         7839 02-APR-1981 00:00:00       2975                    20
          7782 CLARK      MANAGER         7839 09-JUN-1981 00:00:00       2450                    10
          7788 SCOTT      ANALYST         7566 19-APR-1987 00:00:00       3000                    20
          7839 KING       PRESIDENT            17-NOV-1981 00:00:00       5000                    10
          7900 JAMES      CLERK           7698 03-DEC-1981 00:00:00        950                    30
          7934 MILLER     CLERK           7782 23-JAN-1982 00:00:00       1300                    10
    7 rows selected.
    SQL> select * from emp
      2  minus
      3  select * from emp2;
         EMPNO ENAME      JOB              MGR HIREDATE                    SAL       COMM     DEPTNO
          7369 SMITH      CLERK           7902 17-DEC-1980 00:00:00        800                    20
          7499 ALLEN      SALESMAN        7698 20-FEB-1981 00:00:00       1600        300         30
          7654 MARTIN     SALESMAN        7698 28-SEP-1981 00:00:00       1250       1400         30
          7698 BLAKE      MANAGER         7839 01-MAY-1981 00:00:00       2850                    30
          7844 TURNER     SALESMAN        7698 08-SEP-1981 00:00:00       1500          0         30
          7876 ADAMS      CLERK           7788 23-MAY-1987 00:00:00       1100                    20
          7902 FORD       ANALYST         7566 03-DEC-1981 00:00:00       3000                    20
    7 rows selected.If you actually need to know what columns data is different on "non-matching" rows (based on your primary key) then you'll have to compare column by column.

  • Compare two members from the same dimension in HFR

    Hi,
    Is it possibe to compare two members from the same dimension in HFR? The requirement is to compare Year and Week members from the same dimension. The Week date will be selected from POV. The corresponding Year date should be displayed in the report. Week dates are in the format W2008-03-07 and Year dates are in YTD2008-03-07.
    The dates are same except the preceding character.I am unable to compare these two. In my understanding there's no substring or replace functions in HFR.
    Kindly help. Thanks in advance.
    Regards,
    Uma

    Hi,
    How is your database structured? it may be possible to use the 'RelativeMember' function if it will always be the same number of steps between the 'W' member and the 'YTD' member, e.g. if your hierarchy is something like:
    Time
    .Weeks
    ..W2008-03-07
    ..W2008-03-10 etc.. for 52 weeks
    .YTD
    ..YTD2008-03-07
    ..YTD2008-03-10 etc.. for 52 weeks
    In your report select 'Current Point of View for Time' in one row/column and in the other use:
    RelativeMember set up as follows:
    Member: Current Point of View for Time
    Offset: 52
    Hierarchy: Time
    RelativeMemberList: Lev0, Time
    UseFirstDescendant: leave unselected
    Hope this helps
    StuartGame
    www.analitica.co.uk

  • Trigger in mutation - Update another rows in the same table with a trigger

    Hi ,
    I try to do a before update trigger on a table , but the trigger is in mutation. I understand why it do that but my question is :
    How can I update other rows in the same table when a UPDATE is made on my table??????
    Here is my trigger :
    CREATE OR REPLACE TRIGGER GDE_COMPS_BRU_5 BEFORE
    UPDATE OF DEPARTEMENT--, DISCIPLINE, DEG_DEMANDE, CE_ETAB
    ON GDEM.COMPOSITION_SUBV
    FOR EACH ROW
    Organisme : FQRNT-FQRSC
    Date de création : 14-07-2011
    Date de modification :
    Modifié par :
    Auteur : Johanne Plamondon
    Description : Ce déclencheur s'executera lors de la modification
    du responsable dans la table COMPOSITION_SUBV
    DECLARE
    V_OSUSER V$SESSION.OSUSER%TYPE;
    V_PROGRAM V$SESSION.PROGRAM%TYPE;
    V_TERMINAL V$SESSION.TERMINAL%TYPE;
    V_MACHINE V$SESSION.MACHINE%TYPE;
    V_MODULE V$SESSION.MODULE%TYPE;
    V_LOGON_TIME V$SESSION.LOGON_TIME%TYPE;
    V_AUDIT_ID NUMBER;
    vSEQ NUMBER;
    i NUMBER;
    vID DEMANDE.ID%TYPE;
    BEGIN
    begin
    SELECT OSUSER, PROGRAM, TERMINAL,MACHINE,MODULE, LOGON_TIME
    INTO V_OSUSER,V_PROGRAM,V_TERMINAL,V_MACHINE,
    V_MODULE,V_LOGON_TIME
    FROM V$SESSION
    WHERE TYPE = 'USER'
    AND USERNAME = USER
    AND LAST_CALL_ET IN (0,1)
    AND ROWNUM < 2;
    exception when others then null; end;
    IF NVL(:NEW.SC_PART,' ') = 'CHC' THEN
    SELECT COUNT(*)
    INTO i
    FROM DEMANDE
    WHERE DEM_REF = :NEW.DEM_ID
    AND PER_NIP = :NEW.PER_NIP;
    IF i = 1 THEN
    SELECT ID
    INTO vID
    FROM DEMANDE
    WHERE DEM_REF = :NEW.DEM_ID
    AND PER_NIP = :NEW.PER_NIP;
    UPDATE COMPOSITION_SUBV
    SET --CE_ETAB     = :NEW.CE_ETAB,
    --DISCIPLINE  = :NEW.DISCIPLINE,
    DEPARTEMENT = :NEW.DEPARTEMENT,
    --DEG_DEMANDE = :NEW.DEG_DEMANDE,
    DATE_MODIF = SYSDATE,
    USER_MODIF = V_OSUSER
    WHERE DEM_ID = vID
    AND PER_NIP = :NEW.PER_NIP
    AND ANNEE = :NEW.ANNEE;
    END IF;
    END IF;
    /*EXCEPTION
    WHEN OTHERS THEN
    NULL;*/
    END;

    A standard disclaimer, the mutating trigger error is telling you that you really, really, really don't want to be doing this. It generally indicates a major data model problem when you find yourself in a situation where the data in one row of a table depends on the data in another row of that same table. In the vast majority of cases, you're far better off fixing the data model than in working around the problem.
    If you are absolutely sure that you cannot fix the data model and must work around the problem, you'll need
    - A package with a collection (or global temporary table) to store the keys that are modified
    - A before statement trigger that initializes the collection
    - A row-level trigger that adds the keys that were updated to the collection
    - An after statement trigger that iterates over the data in the collection and updates whatever rows need to be updated.
    If you're on 11g, this can be simplified somewhat by using a compound trigger with separate before statement, row-level, and after statement sections.
    Obviously, though, this is a substantial increase in complexity over the single trigger you have here. That's one of the reasons that it's generally a bad idea to work around mutating table exceptions.
    Justin

  • Two triggers in the same table and event

    If I created two triggers on the same table and event (before insert), which of them will be triggered first ?...
    The problem from the beginning is that I created the second one as after insert and in the body of the trigger I wrote (:new.xxx:= value) ... then an error (that it should be before insert trigger or update trigger), so I created it as before update ,,, but I have already before update trigger (for primary key)..... and the problem -I think- which of them start first...
    Can make the second one as after insert and make update statement instead of assigning (:new.xxx:= value).....
    Regards

    If I created two triggers on the same table and event
    (before insert), which of them will be triggered
    first ?...As already mentioned, prior to 11g the order of firing is undetermined.
    The problem from the beginning is that I created the
    second one as after insert and in the body of the
    trigger I wrote (:new.xxx:= value) ... then an error
    (that it should be before insert trigger or update
    trigger), so I created it as before update ,,, but I
    have already before update trigger (for primary
    key)..... and the problem -I think- which of them
    start first...If there is a conflict of interest inside the code then you will have to alter your design principle around this to cater for it. Also consider combining the code into a single before insert trigger to prevent any confusion.
    Can make the second one as after insert and make
    update statement instead of assigning (:new.xxx:=
    value).....Attempting to update or query the same table as is causing the trigger to fire will result in a mutating table error. You can't do this.

  • Comparing two data records of same IDOC

    Hi,
    In PI, we need to compare two data records of same IDOC to figure out if what type change occurred.  For example, BENFIT3 IDOC contains data records tilted "E1BEN04".  When there are multiple "E1BEN04" data records, then we need to compare the data inside them to see whether name, or data of birth or SSN is changed. 
    Has anybody came across this before. Your help is much appreciated.
    Thanks
    -Teja

    If it is very few fields then you could use graphical mapping to determine the changes.

  • Possible solution to avoid deadlock when two inserts happen on same table from two different machines.

    Possible solution to avoid deadlock when two inserts happen on same table from two different machines.
    Below are the details from deadlock trace.
    Deadlock encountered .... Printing deadlock information
    Wait-for graph
    NULL
    Node:1
    KEY: 8:72057594811318272 (ffffffffffff) CleanCnt:3 Mode:RangeS-S Flags: 0x1
    Grant List 2:
    Owner:0x00000013F494A980 Mode: RangeS-S Flg:0x40 Ref:0 Life:02000000 SPID:376 ECID:0 XactLockInfo: 0x000000055014F400
    SPID: 376 ECID: 0 Statement Type: INSERT Line #: 70
    Input Buf: RPC Event: Proc [Database Id = 8 Object Id = 89923542]
    Requested by:
    ResType:LockOwner Stype:'OR'Xdes:0x0000002AA53383B0 Mode: RangeI-N SPID:238 BatchID:0 ECID:0 TaskProxy:(0x00000027669B4538) Value:0x10d8d500 Cost:(0/38828)
    NULL
    Node:2
    KEY: 8:72057594811318272 (ffffffffffff) CleanCnt:3 Mode:RangeS-S Flags: 0x1
    Grant List 2:
    Owner:0x0000000B3486A780 Mode: RangeS-S Flg:0x40 Ref:0 Life:02000000 SPID:238 ECID:0 XactLockInfo: 0x0000002AA53383F0
    SPID: 238 ECID: 0 Statement Type: INSERT Line #: 70
    Input Buf: RPC Event: Proc [Database Id = 8 Object Id = 89923542]
    Requested by:
    ResType:LockOwner Stype:'OR'Xdes:0x000000055014F3C0 Mode: RangeI-N SPID:376 BatchID:0 ECID:0 TaskProxy:(0x000000080426E538) Value:0x30614e80 Cost:(0/41748)
    NULL
    Victim Resource Owner:
    ResType:LockOwner Stype:'OR'Xdes:0x0000002AA53383B0 Mode: RangeI-N SPID:238 BatchID:0 ECID:0 TaskProxy:(0x00000027669B4538) Value:0x10d8d500 Cost:(0/38828)
    deadlock-list
    deadlock victim=process5daddc8
    process-list
    process id=process5daddc8 taskpriority=0 logused=38828 waitresource=KEY: 8:72057594811318272 (ffffffffffff) waittime=2444 ownerId=2994026815 transactionname=user_transaction lasttranstarted=2014-07-25T12:46:57.347 XDES=0x2aa53383b0 lockMode=RangeI-N schedulerid=43 kpid=14156 status=suspended spid=238 sbid=0 ecid=0 priority=0 trancount=2 lastbatchstarted=2014-07-25T12:46:57.463 lastbatchcompleted=2014-07-25T12:46:57.463 clientapp=pa hostname=pa02 hostpid=1596 loginname=myuser isolationlevel=serializable (4) xactid=2994026815 currentdb=8 lockTimeout=4294967295 clientoption1=671088672 clientoption2=128056
    executionStack
    frame procname=mydb.dbo.SaveBill line=70 stmtstart=6148 stmtend=8060 sqlhandle=0x03000800d61f5c056bd3860170a300000100000000000000
    INSERT INTO [dbo].[Prod1] .....
    inputbuf
    Proc [Database Id = 8 Object Id = 89923542]
    process id=process5d84988 taskpriority=0 logused=41748 waitresource=KEY: 8:72057594811318272 (ffffffffffff) waittime=2444 ownerId=2994024748 transactionname=user_transaction lasttranstarted=2014-07-25T12:46:57.320 XDES=0x55014f3c0 lockMode=RangeI-N schedulerid=39 kpid=14292 status=suspended spid=376 sbid=0 ecid=0 priority=0 trancount=2 lastbatchstarted=2014-07-25T12:46:57.440 lastbatchcompleted=2014-07-25T12:46:57.440 clientapp=pa hostname=pa01 hostpid=1548 loginname=myuser isolationlevel=serializable (4) xactid=2994024748 currentdb=8 lockTimeout=4294967295 clientoption1=671088672 clientoption2=128056
    executionStack
    frame procname=pa.dbo.SaveBill line=70 stmtstart=6148 stmtend=8060 sqlhandle=0x03000800d61f5c056bd3860170a300000100000000000000
    INSERT INTO [dbo].[Prod1]....
    inputbuf
    Proc [Database Id = 8 Object Id = 89923542]
    resource-list
    keylock hobtid=72057594811318272 dbid=8 objectname=pa.dbo.prod1 indexname=PK_a id=lock1608ee1380 mode=RangeS-S associatedObjectId=72057594811318272
    owner-list
    owner id=process5d84988 mode=RangeS-S
    waiter-list
    waiter id=process5daddc8 mode=RangeI-N requestType=convert
    keylock hobtid=72057594811318272 dbid=8 objectname=pa.dbo.prod1 indexname=PK_a id=lock1608ee1380 mode=RangeS-S associatedObjectId=72057594811318272
    owner-list
    owner id=process5daddc8 mode=RangeS-S
    waiter-list
    waiter id=process5d84988 mode=RangeI-N requestType=convert

    Don't know. Perhaps these can help. I scanned the second link but didn't see much about Ending Deadlocks. I'd say the Fourth link probably has better information than the first three links. But maybe read them all just in case the Fourth is missing something
    one of the first three have.
    Deadlocking
    Detecting and Ending Deadlocks
    Minimizing Deadlocks
    Handling Deadlocks in SQL Server
    Google search for "SQL Deadlock"
    La vida loca

  • Insert multiple rows into a same table from a single record

    Hi All,
    I need to insert multiple rows into a same table from a single record. Here is what I am trying to do and I need your expertise. I am using Oracle 11g
    DataFile
    1,"1001,2001,3001,4001"
    2,"1002,2002,3002,4002"
    The data needs to be loaded as
    Field1      Field2
    1               1001
    1               2001
    1               3001
    1               4001
    2               1002
    2               2002
    2               3002
    2               4002
    Thanks

    You could use SQL*Loader to load the data into a staging table with a varray column, then use a SQL insert statement to distribute it to the destination table, as demonstrated below.
    SCOTT@orcl> host type test.dat
    1,"1001,2001,3001,4001"
    2,"1002,2002,3002,4002"
    SCOTT@orcl> host type test.ctl
    load data
    infile test.dat
    into table staging
    fields terminated by ','
    ( field1
    , numbers varray enclosed by '"' and '"' (x))
    SCOTT@orcl> create table staging
      2    (field1  number,
      3     numbers sys.odcinumberlist)
      4  /
    Table created.
    SCOTT@orcl> host sqlldr scott/tiger control=test.ctl log=test.log
    SQL*Loader: Release 11.2.0.1.0 - Production on Wed Dec 18 21:48:09 2013
    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.
    Commit point reached - logical record count 2
    SCOTT@orcl> column numbers format a60
    SCOTT@orcl> select * from staging
      2  /
        FIELD1 NUMBERS
             1 ODCINUMBERLIST(1001, 2001, 3001, 4001)
             2 ODCINUMBERLIST(1002, 2002, 3002, 4002)
    2 rows selected.
    SCOTT@orcl> create table destination
      2    (field1  number,
      3     field2  number)
      4  /
    Table created.
    SCOTT@orcl> insert into destination
      2  select s.field1, t.column_value
      3  from   staging s, table (s.numbers) t
      4  /
    8 rows created.
    SCOTT@orcl> select * from destination
      2  /
        FIELD1     FIELD2
             1       1001
             1       2001
             1       3001
             1       4001
             2       1002
             2       2002
             2       3002
             2       4002
    8 rows selected.

Maybe you are looking for