• And here you have a different version that will use only the rows needed. Ideally, you shouldn't have to create the PersonList set and you'll have a table with them that you can join to your personstatus table by something different than the name column.

    I really hope that you have a different database design than the one showed in here.

    DECLARE @FromDt date = '20130101',

    @ToDt date = '20140101';

    WITH cteDays AS(

    SELECT *, DATEDIFF(DD,

    CASE WHEN @FromDt < DateAdded THEN DateAdded ELSE @FromDt END,

    CASE WHEN @ToDt > InactivationDate THEN InactivationDate ELSE @ToDt END) + 1 numdays

    FROM personstatus

    WHERE InactivationDate >= @FromDt

    AND DateAdded <= @ToDt

    ),

    PersonList AS(

    SELECT DISTINCT name

    FROM personstatus

    )

    SELECT p.name, SUM( CASE WHEN numdays > 0 THEN numdays ELSE 0 END) numdays

    FROM PersonList p

    LEFT

    JOIN cteDays d ON p.name = d.name

    GROUP BY p.name;

    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