簡體   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