Sequentially Adding Variable Number of Rows

  • I need to add a number rows together and I'm not sure how to do it.

    I have the following dataset.

    A

    I want to add the previous rows together to get the following.

    B

    Can this be done?

     

  •  --==== Sample data
    Declare @testTable Table (Category char(1), [Month] int, Amount int);
    Insert Into @testTable (Category, [Month], Amount)
    Values ('A', 1, 5)
    , ('A', 2, 5)
    , ('A', 3, 10)
    , ('B', 1, 10)
    , ('B', 2, 10)
    , ('B', 3, 10)
    , ('B', 4, 15);

    --==== Example using sample data
    Select *
    , TotalAmount = sum(tt.Amount) over(Partition By tt.Category Order By tt.[Month] rows unbounded preceding)
    From @testTable tt;

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

  • That's perfect!

    Thanks Jeffrey.

  • You are welcome - thank you for the feedback.

    Jeffrey Williams
    “We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”

    ― Charles R. Swindoll

    How to post questions to get better answers faster
    Managing Transaction Logs

  • This was removed by the editor as SPAM

  • This was removed by the editor as SPAM

  •  

    • This reply was modified 3 years, 2 months ago by  roong.

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply