Populate other column value based on previous row value using t-sql

Hi All,
I have one table with 6 columns, let say ID1, ID2,status, EnteredDate,NewValue, Old Value. Where ID1 is the primary key field
 ID1       ID2       status             EnteredDate        NewValue      
Old Value
  1          XYZ       New              07/12/2012           
ABC               null
  2          XYZ       Renewal        08/19/2012            DEF               
null
  3          XYZ       Cancel           10/21/2012            GHI               
null
  4          ZYX       New              09/15/2012           
BDF               null
  5          ZYX       Cancel           10/21/2012            MNS             
null
  6          MBS       New              05/29/2012           
EXP               null
  7          SBX        New              05/29/2012           
SKS               null
  8          SBX        Renewal        06/21/2012            QSR              
SKS
Basically I need a sql query which should populate Output as below. Status=New will always have old date compared to Renewal and Cancel and also OldValue field will be null always for status=New
Output:
 ID1       ID2       status           EnteredDate        NewValue      
Old Value     Row_Num(based on ID1,ID2,Entereddate)
  1          XYZ       New              07/12/2012           
ABC               null                 1
  2          XYZ       Renewal        08/19/2012            DEF               
ABC                2
  3          XYZ       Cancel           10/21/2012            GHI               
DEF                 3
  4          ZYX       New              09/15/2012           
BDF               null                   1
  5          ZYX       Cancel           10/21/2012            MNS              
BDF                 2
  6          MBS       New              05/29/2012           
EXP               null                  1
  7          SBX        New              05/29/2012           
SKS               null                  1
  8          SBX        Renewal        06/21/2012            QSR              
SKS                2
Thanks in Advance, its very urgent. Pls send me the query ASAP.
RH
sql

Hi,
In case of you are using SQL 2012, you can use new built-in function like LAG, try this;
USE tempdb
GO
CREATE TABLE dbo.Test
ID1 int PRIMARY KEY
, ID2 char(3) NOT NULL
, Status varchar(20) NOT NULL
, EnteredDate date NOT NULL
, NewValue char(3) NOT NULL
, OldValue char(3) NULL
GO
INSERT INTO dbo.Test
(ID1, ID2, Status, EnteredDate, NewValue, OldValue)
VALUES
(1, 'XYZ', 'New', '07/12/2012', 'ABC', null)
, (2, 'XYZ', 'Renewal', '08/19/2012', 'DEF', null)
, (3, 'XYZ', 'Cancel', '10/21/2012', 'GHI', null)
, (4, 'ZYX', 'New', '09/15/2012' ,'BDF', null)
, (5, 'ZYX', 'Cancel', '10/21/2012', 'MNS',null)
, (6, 'MBS', 'New', '05/29/2012', 'EXP', null)
, (7, 'SBX', 'New', '05/29/2012', 'SKS', null)
, (8, 'SBX', 'Renewal', '06/21/2012', 'QSR', 'SKS')
WITH cte
AS
(SELECT ID1, ID2, Status, EnteredDate, NewValue, OldValue
, ROW_NUMBER() OVER(PARTITION BY ID2 ORDER BY ID2) Row_Num
, LAG(NewValue, 1, 0) OVER(PARTITION BY ID2 ORDER BY ID2) NewOldValue
FROM dbo.Test)
SELECT ID1, ID2, Status, EnteredDate, NewValue
, NULLIF(NewOldValue, '0') NewOldValue, Row_Num
FROM cte
ORDER BY ID1, ID2;
Dinesh Priyankara
http://dinesql.blogspot.com/
Please use Mark as answer (Or Propose as answer) or Vote as helpful if the post is useful.

Similar Messages

  • Query! calculation based on previous row value

    Hi,
    ID     Code     Direction     From Amount  To Perct      To Amount
    98     POI     F          5457.00          0     
    77     LKJ     T          0          50      (5457*(50/100))
    56     MNB     T          0          25      (5457*(25/100))How to calculate 'To Amount' with in the select query? To Amount will be calculated on the basis of
    From Amount of the First row multiplied by 'To Perct'
    When I wrote a select statement it's taking 0 as 'From Amount'( Because it's in current row) and giving me 0 as 'To Amount'
    Thanks

    One possibility:
    with t as (
    select 98 id,     'POI' Code,     'F' Direction, 5457.00 FromAmount,          0 ToPerct from dual     union all
    select 77,     'LKJ',     'T',          0,          50 from dual     union all
    select 56,     'MNB',     'T',          0,          25 from dual)
    select id, code, direction, FromAmount, ToPerct,
           (tmax.MaxAmount)*(ToPerct/100) ToAmount 
    from t,
         (select max(FromAmount) MaxAmount from t) tmax ;Results:
            ID COD D FROMAMOUNT    TOPERCT   TOAMOUNT
            98 POI F       5457          0          0
            77 LKJ T          0         50     2728,5
            56 MNB T          0         25    1364,25Regards,
    Miguel

  • Determine variable value based on characteristic row value

    Hi all,
    Am basically looking for a bit of advice from those wiser than myself.
    I have a requirement to build an Activity per Driver report which is essentially a list of cost centres down the page, with Productive Hours (an SKF) in one column, the driver (another SKF) in the next column, and then a calculation.
    Sounds easy, however the SKF for the driver differs depending on the cost centre. . . .
    For example, cost centre 100 might be driven by ACTIV1 whereas cost centre 200 might be driven by ACTIV2 and then cost centre 300 might also be driven by ACTIV1.
    I have come up with 2 possible solutions ;
    1) Set the SKF as an attribute of the cost centre and then use this as the restriction in the report.  Easiest, most standard way of setting it up, however the problem here is that some cost centres use a number of SKFs (represented by a hierarchy node) as their activity driver.  I can't set a hierarchy node as an attribute, so I don't know how this could work for those cost centre with more than one SFK accumulating as their driver.
    2) Maintain a Cost Centre to SKF Driver mapping table in R/3 which is loaded into an ODS in BW.  Create the report using an exit variable for the driver, which queries the ODS to retrieve the appropriate SKF value(s) for each cost centre.  Could this work - not sure how I know which cost centre to retrieve the driver for in the exit coding ?
    Any suggestions would be welcomed.  Surely this can't be a unique problem.
    Many thanks,
    Blair

    I should have explained better before. I have one invoice template and we want to keep it one template for all companies. Each invoice is run individually, each companies footer is different, I am calling multiple headers and footers based on each company. Since the headers and footers are different I need to be able to add different amounts of lines and the end of each invoice depending on that company. I have accounted for the page break in my logic based on the amount lines the page is long. I just need a dynamic variable that I can assign different values on the fly.
    Thanks

  • Analytical function need to work based on previous rows result.

    My data are sorted based on sartdatetime column.but i need the sum(value) based on below condition.
    Condition :
    i need to check with current row with previous rows
    if they are same then i need to sum the value with previous row.
    else i need to start the summation.
    My data like below:
    Rownum     Code     Sartdatetime     Value
    1     4619     12/9/2012 11:00      219
    2     5344     12/9/2012 14:39      27
    3     4619     12/9/2012 15:11     20
    4     4619     12/9/2012 19:33     14
    5     4619     12/9/2012 20:53      16
    6     6851     12/9/2012 21:21      1
    7     4619     12/9/2012 21:22     35
    8     5623     12/10/2012 1:59     4
    9     5623     12/10/2012 2:03 3
    10     5623     12/10/2012 2:06 5
    11     4619     12/10/2012 2:17 1
    12     5623     12/10/2012 2:18     5
    13     5623     12/10/2012 2:25      2
    14     5623     12/10/2012 2:27 2
    15     4619     12/10/2012 2:29      30
    Eg:
    Take the first row. For that no previous rows. So we directly added the value like below.
    Rownum     Code     Sartdatetime     Value sum(val)
    1     4619     12/9/2012 11:00      219 219
    take the seconds row, we can check the code value (5344)with first row value (4619). the values are different . So our summation like.
    2     5344     12/9/2012 14:39      27 27
    for third row , we can check the code value (4619)with second row value (5344). the values are different . So our summation like.
    3     4619     12/9/2012 15:11     20 20
    for fourth row we can check the code value (4619)with second row value (4619). the values are same. So our summation like.
    4     4619     12/9/2012 19:33     14 34 - The sum of previous row result.
    5 th row also same value so
    5     4619     12/9/2012 20:53      16 50T he sum of previous row result.
    then the same value come again in 7 th row so here we need to start the summation like below.
    7     4619     12/9/2012 21:22     35 35.
    i want the result like below.
    Rownum     Code     Sartdate time     Value Expected result
    1     4619     12/9/2012 11:00      219 219
    2     5344     12/9/2012 14:39      27 27
    3     4619     12/9/2012 15:11     20 20
    4     4619     12/9/2012 19:33     14 34
    5     4619     12/9/2012 20:53      16 50
    6     6851     12/9/2012 21:21      1 1
    7     4619     12/9/2012 21:22     35 35
    8     5623     12/10/2012 1:59     4 4
    9     5623     12/10/2012 2:03 3 7
    10     5623     12/10/2012 2:06 5 12
    11     4619     12/10/2012 2:17 1 1
    12     5623     12/10/2012 2:18     5 5
    13     5623     12/10/2012 2:25      2 7
    14     5623     12/10/2012 2:27 2 9
    15     4619     12/10/2012 2:29      30 30
    Please help

    Hi,
    Welcome to the forum!
    Here's one way to do what you want:
    WITH     got_grp_id     AS
         SELECT  code, starttime, value
         ,     ROW_NUMBER () OVER ( ORDER BY      starttime )     AS r_num
         ,     ROW_NUMBER () OVER ( ORDER BY      starttime )
               - ROW_NUMBER () OVER ( PARTITION BY  code
                                         ORDER BY          starttime
                           )                    AS grp_id
         FROM    table_x
    SELECT       r_num
    ,       code
    ,       starttime
    ,       value
    ,       SUM (value) OVER ( PARTITION BY  code, grp_id
                                    ORDER BY          starttime
                      )         AS sum_value
    FROM      got_grp_id
    ORDER BY  starttime
    ;For an explanation of the Fixed Difference technique, see {message:id=9953384} and/or {message:id=9957164}
    Whenever you have a problem, please post CREATE TABLE and INSERT statements for your same data. For example:
    CREATE TABLE     table_x
    (   code     NUMBER (4)
    ,   starttime     DATE          UNIQUE
    ,   value     NUMBER
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/9/2012 11:00', 'MM/DD/YYYY HH24:MI'),
                                            219);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5344, TO_DATE ( '12/9/2012 14:39', 'MM/DD/YYYY HH24:MI'),
                                            27);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/9/2012 15:11', 'MM/DD/YYYY HH24:MI'),
                                            20);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/9/2012 19:33', 'MM/DD/YYYY HH24:MI'),
                                            14);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/9/2012 20:53', 'MM/DD/YYYY HH24:MI'),
                                            16);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (6851, TO_DATE ( '12/9/2012 21:21', 'MM/DD/YYYY HH24:MI'),
                                            1);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/9/2012 21:22', 'MM/DD/YYYY HH24:MI'),
                                            35);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE ( '12/10/2012 1:59', 'MM/DD/YYYY HH24:MI'),
                                            4);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE  ('12/10/2012 2:03' , 'MM/DD/YYYY HH24:MI' ),
                                                       3);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE ( '12/10/2012 2:06', 'MM/DD/YYYY HH24:MI'),
                                            5);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/10/2012 2:17', 'MM/DD/YYYY HH24:MI'),
                                            1);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE ( '12/10/2012 2:18', 'MM/DD/YYYY HH24:MI'),
                                            5);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE ( '12/10/2012 2:25', 'MM/DD/YYYY HH24:MI'),
                                            2);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (5623, TO_DATE  ('12/10/2012 2:27' , 'MM/DD/YYYY HH24:MI' ),
                                                       2);
    INSERT INTO table_x (code, starttime, value)
           VALUES         (4619, TO_DATE ( '12/10/2012 2:29', 'MM/DD/YYYY HH24:MI'),
                                            30);
    COMMIT; See the forum FAQ {message:id=9360002}
    Output:
    R_NUM       CODE STARTTIME             VALUE  SUM_VALUE
        1       4619 12/9/2012 11:00         219        219
        2       5344 12/9/2012 14:39          27         27
        3       4619 12/9/2012 15:11          20         20
        4       4619 12/9/2012 19:33          14         34
        5       4619 12/9/2012 20:53          16         50
        6       6851 12/9/2012 21:21           1          1
        7       4619 12/9/2012 21:22          35         35
        8       5623 12/10/2012 01:59          4          4
        9       5623 12/10/2012 02:03          3          7
       10       5623 12/10/2012 02:06          5         12
       11       4619 12/10/2012 02:17          1          1
       12       5623 12/10/2012 02:18          5          5
       13       5623 12/10/2012 02:25          2          7
       14       5623 12/10/2012 02:27          2          9
       15       4619 12/10/2012 02:29         30         30Edited by: Frank Kulash on Dec 24, 2012 6:44 AM
    Added sample data.

  • Compare previous row values for the same id and decide

    Hello ,
    I have this sample data
    create table #student_academic
    pk_id int identity(1,1) primary key ,
    student_id int ,
    [year] int,
    [aggr_marks] float
    insert into #student_academic
    student_id ,
    [year] ,
    [aggr_marks]
    values
    (112,2012,55.4),(113,2012,65.4),(114,2012,82.32),
    (112,2013,75.4),(113,2013,91.22),(114,2013,45.45),
    (112,2014,61.2),(113,2014,95.2),(114,2014,75.6)
    select * from #student_academic
    from the above data i have to generate an extra status column. this status column should be decided by comparing the previous row value. the exact output should be like below.
    student_id year aggr_marks Staus----------------------------------------------------------
    112 2012 55.4 None
    112 2013 75.4 Promoted
    112 2014 61.2 Demoted
    113 2012 95.2 None
    113 2013 75.6 Demoted
    113 2014 91.22 Promoted
    113 2012 45.45 None
    113 2013 65.4 Promoted
    113 2014 82.32 Promoted
    is there any way to write the t-sql with out using cursors ? this table has around 25GB of data. Any idea would be appreciated.
    Thanks in advance.

    Hello,
    The difficulty of your example is
    that there are several rows for
    the same year and the same student.
    I present a solution
    if there is
    one line per year per
    student:
    TRUNCATE TABLE #student_academicinsert into #student_academic
    student_id ,
    [year] ,
    [aggr_marks]
    values
    (112,2012,55.4),(113,2012,65.4),(114,2012,82.32),
    (112,2013,75.4),(113,2013,91.22),(114,2013,45.45),
    (112,2014,61.2),(113,2014,95.2),(114,2014,75.6)
    Go
    WITH CTE AS
    (SELECT pk_id, student_id, year, aggr_marks,
    (SELECT TOP 1 aggr_marks FROM #student_academic AS b
    WHERE a.student_id = b.student_id AND a.year -1 = b.year
    ORDER BY student_id) AS prev_aggr_marks
    FROM #student_academic AS a
    SELECT
    pk_id, student_id, year, aggr_marks,
    CASE
    WHEN prev_aggr_marks IS NULL THEN 'None'
    WHEN aggr_marks < prev_aggr_marks THEN 'Demoted'
    WHEN aggr_marks >= prev_aggr_marks THEN 'Promoted'
    END AS Status
    FROM CTE
    ORDER BY student_id, year
    Regards,
    Charlie
    Charlie Dancoisne - Independent Consultant & Trainer (Please take a moment to "Vote as Helpful" and/or "Mark as Answer", where applicable. This helps the community, keeps the forums tidy, and recognises useful contributions. Thanks!)

  • How to propogate previous row value

    All,
    I have a query were I need to fill the null data with previous row value. Like I have a table were we record all the On hand quantity for a item for a date. Lets say I have only 2 rows in this table for a month then I am planning to write a view that will give me 31/30 rows for a month and if for a specific date is the value is null then it should read from previous row unitl it finds the data otherwise display 0.
    Ex. Actual table
    Item No Date Qty
    1 1/1/2010 10
    1 1/5/2010 15
    View I have written, I need to fill the null Qty with previous row data
    Item No Date Qty
    1 1/1/2010 10
    1 1/2/2010
    1 1/3/2010
    1 1/4/2010
    1 1/5/2010 15
    1 1/6/2010
    I want something like this how can i do this?
    Item No Date Qty
    1 1/1/2010 10
    1 1/2/2010 10
    1 1/3/2010 10
    1 1/4/2010 10
    1 1/5/2010 15
    1 1/6/2010 15
    Thanks

    Hi Sung, sorry by my delay
    Basically I'm building a Client Framework that a lot of actions are automatically managed, then I extend Objects
    for example EntityImpl. I let to user set any value to the
    database mapped fields but I will check this values
    using my own bussines rules before to insert into database
    and if this values are wrong I display an alert.
    My problem is that I catch insert event to call validate
    functions. But when any value is wrong I will show an alert, but if user commits transaction after validate
    funcion is not revalidated. Well I supose that is a bad implementation for validation rules, now amb reading about
    Validationlistener because I think is the best way to do
    all that I need. I let to the user add field values but
    these values not will commited while validationListeners
    return isValid = true;
    Thanks Sung.
    Albert.

  • Set default value based on current day value and setItems in Design studio

    Hello
    I have 2 filters on my dashboard - year and month. The default display of the dashboard should populate current year data. Is it possible to create formula to populate dynamic default value based on the current date using setSelectedValue() ?
    Also, for the calendar month, the items are set as below
    DD_MONTH.setItems(DS_1.getMemberList("0CALMONTH",
    MemberPresentation.INTERNAL_KEY, MemberDisplay.TEXT, 12, "ALL");
    This displays month values as 01/2014, 02/2014 ... How can I change these value to display as January if mm = 01 and February if mm = 02 etc..
    Thanks
    Sirisha

    Hi Victor,
    I have tried using below statment to populate current year as the default selection value for the dropdown. Used it on Startup, but for some reason it loads all the data when the dashboard is opened the first time. Any ideas?
    DS_1.setFilter("0CALYEAR",[Convert.subString(APPLICATION.getInfo().dateNowInternalFormat, 4,6)]);
    Thanks
    Sirisha

  • Finding all rows based on previous rows column value diffrence

    I have an interesting requirement. There is a DATE column and a user in a table and I have to find all rows for all the user for which the previous row and current row has time difference of lets say more than 30 minutes. Rows are already sorted by time.
    For example in the following table, we need ID 4 and 6 for user 1.
    ID User date
    1 1 today 1 hour 0 min 0 s
    2 1 today 1 hour 1 min 0 s
    3 1 today 1 hour 29 min 0 s
    *4 1 today 1 hour 59 min 3 s*
    5 1 today 2 hour 10 min 2 s
    *6 1 today 2 hour 50 min 7 s*
    Edited by: user733179 on Mar 5, 2009 12:00 PM

    Hi,
    To get all the users in the result set, outer-join to a table (or subquery, as shown bleow) that has one row per user:
    WITH     got_dif     AS
         SELECT     id,     dt,     usr
         ,     (dt - LAG (dt)
                    OVER ( PARTITION BY  usr
                              ORDER BY          dt
              )             -- difference in days
                  * 24 * 60  AS minutes_dif
         FROM     table_x
    --     WHERE     ...     -- if needed
    ,     all_users     AS
         SELECT DISTINCT  usr
         FROM              table_x
    SELECT     gd.id,     gd.dt,     au.usr
    ,     NVL2 ( gd.usr
              , 'Okay'
              , 'Dif is never > 30'
              )    AS flag
    FROM          all_users
    LEFT OUTER JOIN     got_dif          ON  gd.usr         = au.usr
                                AND gd.minutes_dif > 30
    ;Notice that the test for a 30-minute difference is part of the join condition.
    You don't need the flag column, and you may not want it.
    If you would prefer a separate query of just the users that are not in the original result set, then you can use the original query (modified only slightly) as an EXISTS ior NOT IN sub-query. For example:
    SELECT DISTINCT     usr
    FROM    table_x
    WHERE   usr  NOT IN
         WITH     got_dif     AS
              SELECT     id,     dt,     usr
              ,     (dt - LAG (dt)
                             OVER ( PARTITION BY  usr
                                      ORDER BY          dt
                    )             -- difference in days
                        * 24 * 60  AS minutes_dif
               FROM     table_x
    --          WHERE     ...     -- if needed
         SELECT  usr   -- Only 1 column in SELECT clause
         FROM     got_dif
         WHERE     minutes_dif     > 30
    ;

  • DAX - how to use dax to return a previous row value?

    Hi,
    I was trying to use the EARLIER function but couldn't make it work:
    EVALUATE
    SUMMARIZE (
    CALCULATETABLE (
    'Inscricoes',
    'Ano Letivo'[ID_TB_DIM_ANO_LETIVO] <= VALUE(26),
    'Ano Letivo'[ID_TB_DIM_ANO_LETIVO] > VALUE(26) - 5,
    'Escola'[ID_TB_DIM_UNIDADE_ORGANICA] = VALUE(6),
    Curso[ID_TB_DIM_CURSO] = VALUE(372),
    'Tipo de Inscricao no Curso'[DS_TIPO_INSCRICAO_CURSO]
    = "Matrícula"
    'Ano Letivo'[ID_TB_DIM_ANO_LETIVO],
    'Ano Letivo'[DS_ANO_LETIVO],
    "NR_INSCRICOES", [NR_ESTUDANTES_INSCRITOS])
    This generates:
    ID_TB_DIM_ANO_LETIVO
    DS_ANO_LETIVO
    NR_INSCRICOES
    22
    2010-11
    93
    23
    2011-12
    101
    24
    2012-13
    84
    25
    2013-14
    85
    26
    2014-15
    104
    I need a new field that does returns the previous value of subscriptions (NR_INSCRICOES), so last 2 columns will be:
    93 - 
    101 - 93
    84 - 101
    85 - 84
    104 - 85
    Need some help. Thanks

    Hi Pedro,
    According to your description, you want to get the previous row data along with each row. Right?
    In DAX, we can use EARLIER() function to achieve this requirement. Please refer to link below:
    PowerPivot DAX Session Notes 2 – Previous Row
    In this scenario, I suggest you select the three columns into one table(let's say TABLE1). Then you can try the expression below:
    =CALCULATE(MAX(TABLE1[NR_ESTUDANTES_INSCRITOS]), (FILTER(TABLE1,EARLIER(TABLE1[ID_TB_DIM_ANO_LETIVO])>TABLE1[ID_TB_DIM_ANO_LETIVO])))
    Reference:
    EARLIER Function (DAX)
    Best Regards,
    Simon Hou
    TechNet Community Support

  • Hide multiple rows in a dynamic table based on the row value.

    Hi,
    I need to hide multiple rows in a dynamic table based on the specific value of that row.
    I cant find the right expression to do that.
    please help

    Go to the Row Properties, and in the Visibility tab, you have "Show or hide based on an expression". You can use this to write an expression that resolves to true if the row should be hidden, false otherwise.
    Additionally, in the Matrix properties you should take a look at the filters section, perhaps you can achieve what you wish to achieve through there by removing the unnecessary rows instead of just hiding them.
    It's only so much I can help you with the limited information. If you require further help, please provide us with more information such as what data are you displaying, what's the criteria to hiding rows, etc...
    Regards
    Andrew Borg Cardona

  • Looping thru column names based on a variable value

    I have an ArrayCollection with a series of columns named
    price1, price2... thru to price10
    I'm trying to loop thru these columns based on a variable
    value, but can't figure the syntax:
    for (var column:int = 1; column < 11; column++){
    testPrice = myGrid.selectedItem.price(column); <-- this
    doesn't work
    }

    Try testPrice = myGrid.selectedItem["price" + column];
    Remember to test that selectedItem isn't null before you try
    to assign the values.
    TS

  • Compounding using previous row values

    Greetings!
    Im trying to write SQL in Oracle 10.2.0.4. I have no success using OVER , PARTITION analytic functions. Can someone help with this requirement..
    Data :
    with t as (select 1 AS Calc_Seq, 700 as erncd, 0.05 as pct, 22 Hrly from dual union all
    select 2, 701, 0.05 , 22 from dual union all
    select 3, 702, 0.075 , 22 from dual)
    SELECT T.Calc_Seq,T.erncd,T.pct,T.hrly FROM T;
    Output required as follows ...
    Need compounded rate field, as PCT rate of previous row "Compounded rate" field value.
    CALC_SEQ     ERNCD          PCT          HRLY        Compounded rate
    1               700            0.05          22               23.1
    2              701            0.05          22               24.255
    3              702            0.075          22               26.074125Thanks in advance.
    Edited by: Rama on Jan 9, 2013 11:39 AM
    Edited by: Rama on Jan 9, 2013 11:50 AM

    Hi,
    Try this:
    WITH
      t AS
        SELECT      1    AS Calc_Seq    ,700  AS erncd    ,0.05 AS pct  ,22 Hrly  FROM      dual    UNION ALL
        SELECT      2                   ,701              ,0.05         ,22       FROM      dual    UNION ALL
        SELECT      3                   ,702              ,0.075        ,22       FROM      dual
    SELECT
    FROM
      T
    model
    dimension by (calc_seq)
    measures (erncd, pct, hrly, 0 cr)
    rules
    cr[any] order by calc_seq = case  when cv(calc_seq) = 1 then hrly[cv(calc_seq) ] * (1 +pct[cv(calc_seq)])
                                      else cr[ cv() -1] * (1 + pct[cv()]) end
    CALC_SEQ ERNCD PCT     HRLY  CR
           1   700 0.05    22    23.1
           2   701 0.05    22    24.255
           3   702 0.075   22    26.074125 Regards,
    Peter

  • Bulk collect seems to retain previous row value when current returns null

    Dear all,
    I am currently writing package in plsql.
    The main logic of the program is as follow .. Program works fine .. but ... when no data is found for current  V_1, V_2,V_3 , insertion is done with previous cursor row value of V_1,V_2,V_3, ... which is not good.
    I tried to change the last nested cursor with first..last instead of 1..count, but result is the same.
    Any idea?
    open c_trt;
       loop  
       fetch c_trt bulk collect into bk_trig limit v_limit;
         open c_bkeve;
              fetch c_bkeve bulk collect into bk_eve limit v_limit;
                   if bk_eve.count > 0 then
                         for k in 1..bk_eve.count loop;
                             case
                                  when a =1 then    
                                       open c_bkieve(bk_eve(k).age,bk_eve(k).ope, bk_eve(k).eve);
                                            fetch c_bkieve bulk collect into bk_ieve limit v_limit;
                                                 if bk_ieve.count > 0 then
                                                       for j in 1..bk_ieve.count loop
                                                           fetch c_bkieve bulk collect into bk_ieve limit v_limit;
                                                                if bk_ieve.count > 0 then
                                                                  for j in 1..bk_ieve.count loop
                                                                     case bk_ieve(j).a
                                                                         when 'ABC' then
                                                                            V_1 := nvl(trim(bk_ieve(j).b),null);
                                                                         when 'XYZ' then
                                                                            V_2 := nvl(trim(substr(bk_ieve(j).b,1,4)),null);
                                                                            V_3 := nvl(trim(substr(bk_ieve(j).b,6,22)),null);
                                                                          else
                                                                               null;
                                                                         end case;
                                                                     end loop;
                                                                else
                                                                     V_1 := null;
                                                                     V_2 := null;
                                                                     V_3 := null;
                                                                end if;
                                            close c_bkieve;
                        insert into xxx values(V_1,V_2,V_3);
    etc, etc
    Thanks for your help
    Jerome

    Something like this
       select a.dco
            , a.agsa
            , a.agem
            , a.agde
            , a.ope
            , a.eve
            , a.tpr
            , a.nat
            , a.age
            , a.dev
            , a.ncp
            , a.suf
            , a.sen
            , a.dva
            , a.mon
            , a.lib
            , c.cli
         from bmvtg_mi a
         join bcom c
           on a.age = c.age
          and a.dev = c.dev
          and a.ncp = c.ncp
          and a.suf = c.suf 
         join (
                   select x.*
                        , y.cur_char
                     from bkeve_mi x
                     left join wb_currency y
                       on x.csp4 = y.cur_num
              ) b
           on b.age = decode(v_var1, 'age', a.age, 'agem', a.agem, 'agsa', a.agsa, 'agde', a.agde, a.age)
        where exists
                  select *
                    from wb_client sc
                   where c.cli = sc.customer_number
                     and ready = 1
          and exists
                  select *
                    from wb_pdt sp
                   where c.cpro = sp.c_pro

  • Unable to filter LookupSet values based on another Lookup value

    Hey all, I've got a report item where I'm pulling a list of values using a lookupset. The lookupset is working as expected, however I need to filter those results based on a different value which belongs to the same dataset as the lookup value. I'm trying
    to filter on the tablix but nothing I try is working to filter. I just end up with no data when I know I should be getting one value. I tried filtering using a lookup and lookupset expression but that doesn't seem to be what is needed. This is my first time
    really diving into lookups so any help would be appreciated.
    Thanks,
    Bryan
    (using report builder 3.0)

    Do you only want the values where type = "Writing Assignment 1". If that is the case then modify your LookupSet as follows:
    =Join(Lookupset(Fields!identifier.Value+"Writing
    Assignment 1",Fields!Student.Value+Fields!value.Value,
    Fields!value.Value, "Comments"), vbCrLf)
    This will require that identifier matches student and type matches "Writing Assignment 1".
    "You will find a fortune, though it will not be the one you seek." -
    Blind Seer, O Brother Where Art Thou
    Please Mark posts as answers or helpful so that others may find the fortune they seek.

  • Multi Row update using pl/sql anonymous block process

    Does anyone have an example of multi row update using a pl/sql anonymous block process?
    The reason I can not use the apex mru process is that the table in questions has a five field key.
    My attempts have failed with a bad number.
    Thanks,
    Gary

    Hi Gary,
    can y<ou pls send the definition of thet table and the UPDATE sql.
    It is a littel difficult like this.
    We need more info.
    BR,
    Lutz
    =;-)

Maybe you are looking for

  • TS2972 Hone sharing is locked into my old itunes email. How do I change this to my new itunes email address

    My Home PC has the Home Sharing linked to my OLD email address.  How do I change this to me new email address so I can Home Share again?

  • WAP4410N (Repeater-Mode) is crashing at least once a day

    Hello everyone we installed a WAP4410n for a customer who needed a wireless repeater to forward the signal to another part of the building. Everything is configured properly and works, until the device stops responding. This happens at least once a d

  • MiniDP to HDMI: Sound stopped working

    Hi everyone, I have a Macbook Pro and a Mini Display Port to HDMI cable and the sound output just stopped working. I used it last night and it worked perfectly. Now it recognizes that it's connected to my TV, and the display is fine, but when I go to

  • Sales order status not changed

    Even after all line items Delivered and  Accounting document cleared, sales order's status is "Being Processed". SO is still showing open order list in VA05..There are not much changes done in SO...What could be the reason...

  • ASA 5510 cannot connect to Microsoft IAS

    I'm at a total loss here. I am transitioning from a Microsoft ISA server to a Cisco ASA 5510. So far so good, until it comes to getting AAA functioning properly. I have a Microsoft IAS server that is functioning properly, however when I try to test i