How to get sum of date difference from multiple records

  • I have a table created and populated as

    USE Adventureworks

    GO

    CREATE TABLE datesum (id tinyint, name VARCHAR(25),sdate DATETIME, edate DATETIME )

    GO

    INSERT INTO datesum

    SELECT 1,'TestName1','2004-01-25','2005-02-06'

    UNION ALL

    SELECT 2,'TestName1','2003-07-20','2005-03-18'

    UNION ALL

    SELECT 3,'TestName1','2002-12-24','2004-03-21'

    UNION ALL

    SELECT 4,'TestName1','2001-10-27','2003-03-03'

    GO

    Now table has four rows with date records of single person. I am required to calculate the sum of datediff of all of records of a given person in days.

    For example in datesum records i require total days as 1930 days. Please some efficient way for it preferably by avoiding cursors.

    Regards

    DBDigger Microsoft Data Platform Consultancy.

  • Just write what you said...

    DECLARE @datesum TABLE (id tinyint, name VARCHAR(25),sdate DATETIME, edate DATETIME )

    INSERT INTO @datesum

    SELECT 1,'TestName1','2004-01-25','2005-02-06'

    UNION ALL

    SELECT 2,'TestName1','2003-07-20','2005-03-18'

    UNION ALL

    SELECT 3,'TestName1','2002-12-24','2004-03-21'

    UNION ALL

    SELECT 4,'TestName1','2001-10-27','2003-03-03'

    SELECT SUM(DATEDIFF(DAY, sdate, edate)) FROM @datesum

    Greets

    Flo

  • Thanks, its good.

    DBDigger Microsoft Data Platform Consultancy.

  • florian.reischl (3/5/2009)


    Just write what you said...

    DECLARE @datesum TABLE (id tinyint, name VARCHAR(25),sdate DATETIME, edate DATETIME )

    INSERT INTO @datesum

    SELECT 1,'TestName1','2004-01-25','2005-02-06'

    UNION ALL

    SELECT 2,'TestName1','2003-07-20','2005-03-18'

    UNION ALL

    SELECT 3,'TestName1','2002-12-24','2004-03-21'

    UNION ALL

    SELECT 4,'TestName1','2001-10-27','2003-03-03'

    SELECT SUM(DATEDIFF(DAY, sdate, edate)) FROM @datesum

    Greets

    Flo

    Yep I agree with you florian ....just write what you said!

    :hehe:

    ============================================================
    SELECT YOUR PROBLEM FROM SSC.com WHERE PROBLEM DESCRIPTION =
    http://www.sqlservercentral.com/articles/Best+Practices/61537/[/url]

Viewing 4 posts - 1 through 3 (of 3 total)

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