Domanda

I am using SQL Server 2008 R2.

I have a table in database with records as shown below :

Id | Status   | UserId | StatusDate              | ProgramStartDate

1  | Active   |1       | 2014-04-02 00:00:00.000 | 2014-03-23
2  | Inactive |1       | 2014-04-05 00:00:00.000 | NULL
3  | Pause    |1       | 2014-04-07 00:00:00.000 | NULL
4  | Inactive |1       | 2014-04-10 00:00:00.000 | NULL
5  | Active   |1       | 2014-04-14 00:00:00.000 | NULL

ProgramStartDate is any date that is inserted by user. While StatusDate is actual date-time whenever user have inserted/updated his Status.

Now, I want to count the number of days from ProgramStartDate (2014-03-23) to Today's date (GETDATE()) excluding the number of days in which user was in Inactive status.

Here, user is Active from ProgramStartDate 2014-03-23 to 2014-04-05 (13 Days), 2014-04-07 to 2014-04-10 (3 days), and 2014-04-14 to GETDATE() (9 days) So total number of active days = 13 + 3 + 9 = 25 days.

The formula work is like below example :

'2014/03/23'    '2014/04/05'    13
'2014/04/05'    '2014/04/07'    -2
'2014/04/07'    '2014/04/10'    3
'2014/04/10'    '2014/04/14'    -4
'2014/04/14'    GetDate()   9

and total = 25 days.

Is there any way to achieve this Total Number of Days by SQL query?

È stato utile?

Soluzione

here is the solution for your query. try it now.

Select SUM(TDays) SumDays
From (
Select Id, Status, UserId, 
    Case When (Status = 'Inactive') Then 0 Else
        (DATEDIFF(DAY,StatusDate,(Case When (NextDate IS NULL) Then GetDate() Else NextDate End)))
    End TDays
From (
    Select Id, Status, UserId, Case When (ProgramStartDate IS NOT NULL) Then ProgramStartDate Else StatusDate End StatusDate,
        (Select Min(StatusDate) From StatusMast M Where M.StatusDate > S.StatusDate) NextDate
    From StatusMast S
) As Stat
)As TotDay

Your output is :

SumDays
25
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top