Compare values between records.

Hi Experts,

Looking for your help frame a SQL for logic.

I have a table of the source with the following values of records.

EMP_NO QTR YEAR CD AMT
-----------------------------------------------------------------------
4181537 4 2011 764913.57 QR
4181537 4 2011 WC 864913.57
4181537 4 2011 WC 964913.57
4181537 4 2011 WC 964913.57
4181537 4 2011 WC 964913.57



Desired output:

EMP_NO QTR YEAR CD AMT
-----------------------------------------------------------------------

4181537 4 2011 764913.57 QR
4181537 4 2011 WC 100000.00
4181537 4 2011 WC 100000.00
4181537 4 2011 WC 0.00
4181537 4 2011 WC 0.00


Logic:

Only for the type of recording CD = WC, I need to get the value of the amount not remove with the old amount. Means,

2nd record amount would be.

864913.57 - 764913.57 = 100000.00

3rd record would be,.

964913.57 - 864913.57 = 100000.00

record of 4 th amount would be.

964913.57 - 964913.57 = 0.00

record of 5 th amount would be.

964913.57 - 964913.57 = 0.00


Can you please help me framing a SQL for this logic. Any help would be very apprecirated.

Thank you
K

This way:

with data as
(
  select 1 id, 4181537 no,  4 qtr, 2011 yr, 'QR' cd, 764913.57 amt from dual union all
  select 2, 4181537, 4, 2011, 'WC', 864913.57 from dual union all
  select 3, 4181537, 4, 2011, 'WC', 964913.57 from dual union all
  select 4, 4181537, 4, 2011, 'WC', 964913.57 from dual union all
  select 5, 4181537, 4, 2011, 'WC', 964913.57 from dual
)
select id, no, qtr, yr, cd, amt,
       case
        when cd = 'QR'
          then amt
        when cd = 'WC'
          then amt - lag(amt) over (partition by no order by cd, rownum)
        else
          null
       end diff_amt
  from data;

ID                     NO                     QTR                    YR                     CD AMT                    AMT
---------------------- ---------------------- ---------------------- ---------------------- -- ---------------------- ----------------------
1                      4181537                4                      2011                   QR 764913.57              764913.57
2                      4181537                4                      2011                   WC 864913.57              100000
3                      4181537                4                      2011                   WC 964913.57              100000
4                      4181537                4                      2011                   WC 964913.57              0
5                      4181537                4                      2011                   WC 964913.57              0         

Tags: Database

Similar Questions

  • Compare values between two tables

    Hello

    I have a table named TABLE1 and a table called TABLE2. The tables have a field called NAME.

    I would like to know if all the names (the values of the fields NAME) TABLE2 are a subset of names (the NAME field values) of TABLE1.

    Can you help me?

    Thank you in advance.

    know the values that r in table1 and table2 no

    use

    SELECT name from table1
    less
    Select the name of table2

    and know the values that r not in table1 and table2

    use

    Select the name of table2
    less
    SELECT name from table1

  • Values between removal of special characters

    Hi all

    I'm using the version of oracle 10.2

    create table
    CREATE TABLE DMM.foretst
    (
      lastname       varchar2(20 BYTE)
    );
    INSERT orders
    insert into foretst  (lastname) values
    ('ted'); 
    
    insert into foretst  (lastname) values
    ('teddy {abc}'); 
    
    insert into foretst  (lastname) values
    ('paul #'); 
    
    insert into foretst  (lastname) values
    ('paul #ggg#'); 
    
    insert into foretst  (lastname) values
    ('parker #'); 
    
    insert into foretst  (lastname) values
    ('ash 1'); 
    
    insert into foretst  (lastname) values
    ('$123$ vini'); 
    power required
    lastname
    ted
    teddy
    paul
    paul
    parker
    ash
    vini
    I know how to remove special characters. How to remove values between two special characters?

    any help is appreciated.

    Thanks in advance

    Something like that...

    Ranit>> select
      2  regexp_replace(lastname,'[^a-zA-Z]+(.)*[^a-zA-Z]+','')
      3  from foretst;
    
    REGEXP_REPLACE(LASTNAME,'[^A-ZA-Z]+(.)*[^A-ZA-Z]+','')
    ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    ted
    teddy
    paul
    paul
    parker
    ash
    vini                                                                                                                                                                                                                        
    
    7 rows selected.
    
  • Exchange of values between two columns

    I have a MEMBERS_SYSTEMS_ID table with three columns ID, B1, B2.
    I need to swap values between B1 and B2 for particular values of ID.
    IAM trying the following but is not working, please help solve + [If you can also tell why my SQL does not work which would be awesome] +.

    BEGIN
    DECLARE the temp varchar (50)
    UPDATE MEMBERS. MEMBERS_SYSTEMS_ID

    SET temp = B2,
    B2 = B1,
    B1 = temp
    WHERE ID IN ('85 ', ' 86');
    END

    You cannot update a variable as part of an update, only columns in the table. And, in fact, you don't have an intermediate variable, just do the update directly as:

    SQL> SELECT * FROM t;
    
            ID DESCR1     DESCR2
    ---------- ---------- ----------
             1 Descr2     Descr1
             1 Other2     Other2
             2 Two1       Two2
    
    SQL> UPDATE t
      2  SET descr1 = Descr2,
      3      descr2 = descr1
      4  WHERE id = 1;
    
    2 rows updated.
    
    SQL> SELECT * FROM t;
    
            ID DESCR1     DESCR2
    ---------- ---------- ----------
             1 Descr1     Descr2
             1 Other2     Other2
             2 Two1       Two2
    

    John

  • How to exchange values between ASP and Flash?

    Hello, I want to swap values between ASP and Flash. I don't want to send it in the form of a querstring as:

    myswf.swf? var1 = value.

    I don't want my user to see or change this value.

    Thank you

    Use the urlloader class.

  • By comparing the two records and return only the differences

    Hi all!

    Assume the records as follows:
    USERID     USERNAME   STREET   CITY   PHONE        
    ---------- ---------- -------- ------ -------------
             1 John Smith Street 1 City 1              
             1 John Smith Street 1 City 1 (31) 234-1234
    UserID is PK on this table. Imagine that this application represents two versions of the same record on a table. This recording was 'day' and the phone field changed from null to "(31) 234-1234'.»

    What I´d like to do is to retrieve only (or fields) that changed between these 2 versions of the same record. The idea is to call this query (or process PLSQL) a trigger and save these data on a table. The data returned by the query (or process), on the example above, should be something like:
           USERID     USERNAME STREET CITY PHONE        
    ---------- -------- ------ ---- -------------
             1                      (31) 234-1234
    1 row selected.
    If two columns have been modified, (Eg., City column also changed "City 1' to 'city 12'), the return value should be:
    USERID     USERNAME STREET CITY   PHONE        
    ---------- -------- ------ ------ -------------
             1                 City12 (31) 234-1234
    1 row selected.
    Any idea?
    Thank you very much for your attention.

    Hello

    What I´d like to do is to retrieve only (or fields) that changed between these 2 versions of the same record. The idea is to call this query (or process PLSQL) a trigger and save these data on a table.

    Looks like you're simply wanting a trigger?

    Something like:

    CREATE OR REPLACE TRIGGER audit_trg
      AFTER UPDATE ON your_table
      FOR EACH ROW
    BEGIN
    
     INSERT INTO audit_table(userid, username, street, city, phone)
     VALUES(
       :new.userid,
       nullif(:new.username, :old.username),
       nullif(:new.street, :old.street),
       nullif(:new.city, :old.city),
       nullif(:new.phone, :old.phone)
     );
    
    END;
    /
    
  • Average of all values between (above first and last above) a threshold value.

    Currently I have a VI where I programmed a year or more ago, takes any value of a set of data that exceeds a certain threshold. It is used to capture the average of all values above a threshold when there is a peak of the values that exceed this threshold. However, when there are two or more peaks that exceed this threshold, only values greater than this value are averaged, so the final result is the average of the two or more.

    What I need is for each value that occurs after the threshold is reached, and before that the threshold fell below for the last time. Imagine a set of data whose graph looks like the letter "M" for example with the threshold being to halfway to the top of the M, I want to show the average (the first bump, the fall below the bumps, as well as the last bump) but what I'm saying now is the average of (the first bump, over the last bump). What I get now cut the data between the two summits.

    Any help would be appreciated of course.

    Here's a method, perhaps not the best.

  • Pass parameter value between c# and TestStand

    Hello

    I'm currently futured, customize the User Interface complete

    I Test.seq master who has all the tests and I need to run only the selected test user in the user interface.

    so I thought to transmit the selected user code c# UserInterface test form to master Test.seq.

    How can I pass the value of the parameter or is there another way I can share data between USerINterce and seq file?

    Thanks in advance

    IVI


  • Passing values between tabs, using a structure of housing.

    At the risk of exposing my ignorance, I have a problem of substance; How to pass values in a controlled tab structure of the case.

    I have a simple user interface that uses a control tab control container a structure of all cases wrapped in a while loop. I use

    LabVIEW 2012.

    The basic intent is to run VI in tab 1, whose results would be available for the VI tab 2 ect...

    (See the attached example; an experience I wish that changes to the controls to page 1 int & string will appear

    the indicators corresponding to page 2).

    I can "pass" the values of a case outside the case itself (through a tunnel of output) structure, but can't seem to do

    available for all other cases by a tunnel entrance.

    I tried to tunnel of the case in a registry to lag on the while loop, but am upset by retrieving that data again in another case.

    I tried to use local variables, but obviously do not understand the paradigm brought LabVIEW for variables. I can create a local

    variable but can't seem to 'plug in' to an indicator on the second page.

    First question: is a reasonable method for execution of the loop control program structure business controlled within a certain time tab?

    I chose it because I have literally dozens of parameters to define, validate and want to manage Visual space

    for the operator. For example, I would that this sequence:

    1. Question and list of facilities available on my PC
    2. Select a device to use, make sure it works properly
    3. Set the parameters for this particular device (30)
    4. run the device, collect data and save the results

    Second question: it is clear that I don't know how to use variables, and the examples I read involve transmission of data to parallel structures

    and not in a case. Is a local variable to a reasonable method of transmission of data between the "tabs"? I will gladly make

    accept the reprimand to 'RTFM' until 'FM' required is identified.

    Thank you in advance for your kind attention to my wisely first year survey

    Shift registers are simple to get data from.  Where is your problem with their use?  However, have you considered just using the terminals directly in the case of the Page 2?

    You must learn to use the Structure of the event.  You shouldn't care what tab you are on.  It's all in the same VI.  Therefore use a Structure unique event for all your control value changes.

  • extract the value between the _ or until the end

    Hello

    I was trying to extract a value from format using regexp_substr below. But I don't know how to use the REGEXP_SUBSTR for this. Can someone please help on this.

    STRING

    ORACLE_TECHNOLOGY

    ORACLE_TECHNOLOGY_NETWORK

    ORACLE_TECHNOLOGY_NETWORK_INDIA

    output:

    TECHNOLOGY

    So, what can be the input string, the output should be the string between the 1st and 2nd underscore (_). If missing the 2nd terms underscore (_), then it should give to the end.

    My version of oracle's 11g.

    Oracle Database 11 g Enterprise Edition Release 11.2.0.3.0 - 64 bit Production

    PL/SQL Release 11.2.0.3.0 - Production

    "CORE 11.2.0.3.0 Production."

    AMT for 64-bit Windows: Version 11.2.0.3.0 - Production

    NLSRTL Version 11.2.0.3.0 - Production

    regexp_substr (String, ' _ ([^ _] *)(_|$)', 1, 1, null, 1)

    or

    substr (String, instr (string, '_') + 1, decode (instr (string, '_', 1, 2), 0, Length - instr (string, '_', 1, 2), instr (string, '_', 1, 2) - instr (string, '_', 1, 1) - 1))

  • Extract the value between the xml tags in the XML inside the BLOB field

    Hello

    I have a table that contains a BLOB column, this XML file to store column that received from an external source. Now for one of my needs. I need to read that value is the specific XML tag and create the entry in the database.

    Column name DataType
    IDNumber
    RecordBLOB OBJECT

    This is the XML code that is stored in the file inside the BLOB field format. XML below, I need go get AMC1234 there is after < itemName > text < / itemName > I thought to use XMLTYPE, but unfortunately my DBA team does not XML database, I now use UTL_RAW. CAST_TO_VARCHAR2 and recovery entire string, but I am not able to read actual result it takes. Can someone help me remove AMC1234.

    <? XML version = "1.0"? >

    <! DOCTYPE importFile SYSTEM "xyz.dtd" >

    -< importFile >

    -< importResult >

    < mode status = "DΘFINIR" > general failure < / status >

    < statusCode > 1 < / statusCode >

    invalid < errorMsg > list and holiday component < / errorMsg >

    -< returnInfo >

    < itemName > PRQ < / itemName >

    < Valeurelement > CBA < / Valeurelement >

    < / returnInfo >

    -< returnInfo >

    < itemName > LMP < / itemName >

    < Valeurelement > CBA < / Valeurelement >

    < / returnInfo >

    -< returnInfo >

    < itemName > KEY < / itemName >

    < Valeurelement > 9999 < / Valeurelement >

    < / returnInfo >

    -< returnInfo >

    < itemName > text < / itemName >

    < Valeurelement > AMC1234, FIXED_ALL, RED < / Valeurelement >

    < / returnInfo >

    < / importResult >

    < / importFile >


    Thank you

    Without

    Without - try something like...

    with t as (select"

    -

    -

    General failure

    1

    component and invalid vacation list

    -

    PRQ

    ABC

    -

    LMP

    ABC

    -

    KEY

    9999

    -

    Text

    AMC1234, FIXED_ALL, RED

    "the double pass."

    )

    Select Replace (regexp_substr (col,'([^<>']) itemName))

    , replace (regexp_substr (col,'([^<>""]) Valeurelement))

    t

    connection of level <=> ');

  • Field image cannot refresh when you move between records in a jsf page

    In jdev 12.1.2

    I have a formlayout in a jsf page, there is an af:image that bind to a url of the image file, the source code is like this:

    ("#{bindings.") Headpicurl.inputValue}')

    < f: facet = '3' tab name >

    < af:panelFormLayout id = "pfl1" >

    < af:inputText value = "#{bindings." Id.inputValue}"label =" #{bindings. " ID.hints.label}.

    required = "#{bindings." ReadOnly ID.hints.Mandatory}' = 'true '.

    columns = "#{bindings." Id.hints.displayWidth}.

    maximumLength = "#{bindings." ID.hints.Precision}.

    shortDesc = "#{bindings." ID.hints.ToolTip}"id ="it1">

    < f: validator binding = "#{bindings." ID. Validator} "/ >"

    < / af:inputText >

    < af:image shortDesc = "#{bindings." Headpicurl.hints.ToolTip}"id ="it4.

    source = "#{bindings." Headpicurl.inputValue} "/>"

    < f: facet name = "footer" >

    < af:panelGroupLayout layout = "horizontal" id = "pgl1" >

    < af:button actionListener = "#{bindings." First.Execute text}"="First"

    Disabled = "#{!}" bindings. PartialSubmit First.enabled}"="true"id ="b1"/ >

    < af:button actionListener = "#{bindings." Previous.Execute text}"="previous ".

    Disabled = "#{!}" bindings. PartialSubmit Previous.enabled}"="true"id ="b2"/ >

    < af:button actionListener = "#{bindings." Next.Execute text}"="next ".

    Disabled = "#{!}" bindings. PartialSubmit Next.enabled}"="true"id ="b3"/ >

    < af:button actionListener = "#{bindings." Last.Execute text}"="Last ".

    Disabled = "#{!}" bindings. PartialSubmit Last.enabled}"="true"id ="b4"/ >

    < / af:panelGroupLayout >

    < / f: facet >

    < / af:panelFormLayout >

    < / f: facet >

    But when I browse the records on the page, other areas will be update correctly, except for the field of the image - the image field showing will not refresh.

    Can someone help?

    Thank you.

    so I the records of buttons and update Navigation to set null values from Headpicurl to a valid value, the value of the PartialTriggers property of this image tag.

    Then, the page will be updated correctly for all areas, including the field of view when do the record navigation.

    But after I have erased the property PartialTriggers of this image tag and reload the page, or even restart the jdev, it still works OK now!

    -Then setting this property PartialTriggers the real cause of the previous question of no image field refresh?

    Well, you also updated your nulls to the actual URL so maybe posing (in combination with the caching of the browser)?

    General approach to prevent caching of web resources is the addition of random string to the url of the resource (as suggested by Cvele) or you can write custom servlet which will serve as a proxy and add http headers (non-cache, non-store, must-revalidate expires,...) to prevent caching.

    Anyway, now I have to get rid of the question above. However, a new problem emerges:

    When I update and validation records the attributes of the database. the fields in the jsf page will not display the newly modified database records even if I refreshed the browser or press F5.

    Only after that I open the jsf page in a new browser window, database changes will appear.

    -Is caused by the caching of the browser? and how to fix it?

    How you exactly "update and validation" records (in the same application or a different app/session)?

    If you do this session or different application then you must run query VO again.

    Dario

  • How to find values between two months (from January to the month prompted)?

    Hello

    I need to create a filter on the name of the month. That is to say of January of the year for the 'guest' month of guest of dashboard.

    Ex: If I ask year and month of year in 2013 and March respectively. I should get values for Jan 2013, 2013 Feb and March 2013.

    I can't try one between because that it only works on numeric values.

    I can't have a number of months in prompt because this isn't the condition and I am not allowed to.

    I tried the below query report filter

    «Sun - times» "" Fiscal month "< = (select"Dim - time". "" Fiscal month "where"Dim - time. " ("' Name of the fiscal month ' = @{PMonth}) PMonth where is the Variable of presentation" for months ".

    But it's not working

    Help, please

    Thank you

    If it is 11g then try to use the column twice.

    Thank you

    http://cool-bi.com

  • Color change of values between Illustrator and InDesign

    I have googled and looked here for an answer to my question, but have not been able to find anything.

    I designed several pieces of encumbered asset, all using the same unique color. Some of the pieces I designed in Illustrator and the other in InDesign.

    The problem is, when I copy and paste the yellow color value (if it is RGB or CMYK - I tried both ways), it CHANGES between Illustrator and InDesign. The color stays the same between Illustrator documents, but if I C + P InDesign - or vice versa-, the color value change literally before my eyes. And I don't want to say 'looks like' different, real changes in number.

    Here's a real example:

    Call a box in Illustrator and chose the color #f8f1e0 / 2% 3% 12% 0%. Call a box in InDesign, C + P had the values of color in there, and it DID change the color appropriate for a moment. You click OK. Click New in the color picker and color is now #f8f1e1 / 2% 3% 11% 0%.

    If it is relevant, it seems that the color will change to a slightly darker every time.

    And Yes, the two documents has STARTED OUT as CMYK documents and stayed like that. I also have my color sync via Bridge. I'm working on CC 2015 and all programs are up to date.

    Any idea of what could happen? Thank you in advance.

    ETA: Okay, I just chose preview overprinting in Illustrator and also changed the color of #f8f1e0 to #f8f1e1. I see now this is not a malfunction of the program, but can someone explain WHY this happens? I'm still new to color management and it's quite confusing for me. Thank you once again.

    ETA: thing: when I save the InDesign document to readable PDF and then pull it in Illustrator, the color is now #f8f2e2, even when you preview overprinting.

    Hexadecimal values are RGB color, so if you plug one in the color chart the resulting CMYK values are a conversion of the color management of the profile the document CMYK document RGB profile. You will get different CMYK conversions according to the profile source RGB, CMYK destination profile, intend to color and compensation of the black point used for the conversion.

    In addition the InDesign documents can have colors RGB and CMYK with CMYK and RGB profiles assigned that do not necessarily correspond to the color settings work profiles, in order to sync'ng your color settings may not get everything to match.

    Ultimately if you want to match the CMYK color or nuances between AI and ID, make sure you document assigned CMYK profile matching (Edit > assign profile...) and enter CMYK and hex does not values

  • Display the default value between Dates in guest of dashboard

    OBIEE 11 g

    My users would say the default values shown in my dashboard of the guests. So far, I have created a guest of Dashboard using between operator for dates between CURRENT_DATE - 7 and CURRENT_DATE through SQL results. However, when the dashboard is running the date fields are blank and have not of these dates. Does anyone know how to get these to display. Thanks in advance.

    Instead of current_date-7 you can try with timestampadd(SQL_TSI_DAY,-7,current_date) and
    TIMESTAMPADD(SQL_TSI_DAY,0,CURRENT_DATE)

    It should work.

Maybe you are looking for

  • iPhone contact

    After updating my iPhone IOS 9.3, all my phone past contacts 5.

  • How can I delete the images I posted in threads?

    I came here before and I've posted questions to people to help me. That being said, I sometimes had to post images to show the people what I was talking about. I find this kind of insecure, so I wanted to make sure I deleted all the images that I had

  • How can I activate WiFi in 2049 44 q?

    Hi all How can I turn on wireless in g410 2049 44 q network adapter? I cud on bluetooth but no wi - fi? I'd appreciate your help...

  • Update for Windows XP KB967715

    When I turn on my computer at the bottom left of the screen, I have the yellow icon indicates that the computer should be updated. I install this update. The next day, when I turn on the computer again. I get the same information that the computer ne

  • SimplePass 2011 problem

    A few days ago my new TouchSmart 520-1030, began to connect to a temporary profile at startup. Investigation revealed that a TrueSuiteService of the Image was breaking and had the open register/profile, not allowing not window to use my normal profil