简体   繁体   English

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

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

I am using SQL Server 2008 R2 . 我正在使用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. ProgramStartDate是用户插入的任何日期。 While StatusDate is actual date-time whenever user have inserted/updated his Status. StatusDate是用户插入/更新其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. 现在,我想天从数 计数 ProgramStartDate (2014-03-23) to Today's date (GETDATE())不包括天中,用户在非活动状态的数量。

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 . 在这里,用户是主动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天

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

Is there any way to achieve this Total Number of Days by SQL query? 有什么方法可以通过SQL查询达到此总天数?

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

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

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