SQL Server从日期范围中获取天数,不包括特定日期范围中的特定天数

SQL Server从日期范围中获取天数,不包括特定日期范围中的特定天数,sql,sql-server,sql-server-2008,sql-server-2005,sql-server-2008-r2,Sql,Sql Server,Sql Server 2008,Sql Server 2005,Sql Server 2008 R2,我使用的是SQLServer2008R2 我在数据库中有一个表,记录如下: 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 |

我使用的是
SQLServer2008R2

我在数据库中有一个表,记录如下:

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
是用户插入的任何日期。而
StatusDate
是用户插入/更新其状态时的实际日期时间

现在,我想计算
ProgramStartDate(2014-03-23)到今天日期(GETDATE())
天数,不包括用户处于非活动状态的天数

在这里,用户从
ProgramStartDate
2014-03-23到2014-04-05
13天)、
2014-04-07到2014-04-10
3天)和
2014-04-14到GETDATE()
9天)处于活动状态 因此,活动天数总数=13+3+9=25天

公式功如下例所示:

'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
总计=25天


有没有办法通过SQL查询来实现总天数?

以下是查询的解决方案。现在试试看

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
您的输出是:

SumDays
25

如果还有什么事,请告诉我