Experts Please I Need help to create a sequential aggregate of a column using sum in tsql

  • I need help to create a sequential aggregate of a column using sum in tsql.

    I want a column that will sum up all hours work by transaction date.

    for example

    Monday my hours work will be 8 and therefore my total transaction hours will be 8.

    Tuesday my hours work will be 8 but I want the total hours of my total transaction hours to 16.

    Wed my total hours work will be 5 and I want the total hours of my total transaction hours to 21. etc.

    Select myname, weekday, hours worked, Totalhours_ToDate =Sum(hours worked)

    from table

    Please let me know if I need to explain more.

  • What you are looking for is a running total. Will need more information, DDL for the table (CREATE TABLE statement), sample data (INSERT INTO statements), expected results based on the sample data. Business rules will also be needed to know exactly how the totals are generated.

    Need help with all this, read and follow the instruction in the first article referenced below in my signature block.

  • In 2012+ versions, you can use the OVER() clause for this.

    In 2008 and previous versions, there are different methods which are fully explained in here along with a performance comparison:

    http://www.sqlservercentral.com/articles/T-SQL/68467/

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Luis Cazares (8/17/2015)


    In 2012+ versions, you can use the OVER() clause for this.

    In 2008 and previous versions, there are different methods which are fully explained in here along with a performance comparison:

    http://www.sqlservercentral.com/articles/T-SQL/68467/

    Exactly the article I thought of when I saw the subject. 😛

  • Thanks all for your help. But this link here helped me out

    http://www.sqlteam.com/article/calculating-running-totals

  • I hope that you're not using the triangular joins methods as they're very slow. If you want to know the reason, it's explained in here: http://www.sqlservercentral.com/articles/T-SQL/61539/

    For the cursor option, you shouldn't keep the default settings. A better option is to define it as LOCAL FORWARD_ONLY.

    Don't forget to include the ORDER BY when you define your cursor.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2

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

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