繁体   English   中英

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

[英]SQL Server get number of days from date range excluding certain days from specific date range

我正在使用SQL Server 2008 R2

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

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是用户插入/更新其Status时的实际日期时间。

现在,我想天从数 计数 ProgramStartDate (2014-03-23) to Today's date (GETDATE())不包括天中,用户在非活动状态的数量。

在这里,用户是主动ProgramStartDate 2014-03-23 to 2014-04-05 (13天), 2014-04-07 to 2014-04-10 (3天), 2014-04-14 to 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM