Search code examples
ssiscomputationderived-column

Calculate Difference between current and previous rows in SSIS


How to Calculate Difference between current and previous rows in SSIS then use that result to add a new column to the existing table


Solution

  • I'm assuming when you say "current and previous rows" is

    1. Create 2 package variables, lets say: 'NumBefore'and 'NumAfter'. Both are Int32.
    2. Inside the Data Flow Task, use a source component (lets say OLEDB Source) and select if its a table or a query. Lets say a table T
    3. Drag 'Row Count' in the Data Flow Transformations list. Double click it and in the Section Variable Names, select the variable 'User::NumBefore'. Row Count task will save, in runtime, the result of the calculation in that variable.
    4. Do whatever you want to do with the data extracted from table T. My guess is that you are going to insert new rows in the same table T, right?
    5. You have to use a second Data Flow Task in the Control Flow. Inside drag another OLEDB Source with the same table T. Use another Row Count Task, but this time use the variable 'User::NumAfter'. After the Row Count Task use either a Script Component or a derived column.
    6. If you use Derived Column, write a name for the column, choose the option 'Replace xxxx' if you want to replace the value of xxx column, or 'Add column' if you want to add that as a column output.
      1. In expression, write: @[User::NumAfter] - @[User::NumBefore]. and the place your OLEDB Destination.

    Hope this was you were looking for