簡體   English   中英

獲取兩個日期之間特定月份和年份的天數 SQL

[英]Getting number of days for a specific month and year between two dates SQL

我想檢索重疊特定月份的兩個日期之間的天數。

例如 :

Month = 1 
Year = 2020 
StartDate ='2019-11-12' 
ENDDate ='2020-1-13' 

Result = 13 days

13 因為所選月份中的日期之間有 13 天:2020 年 1 月


其他示例:

Month=9 
Year =2019
StartDate = '2019-8-13' 
ENDDate ='2020-1-1' 

Result = 30 days

30 因為所選月份中的日期之間有 30 天:2019 年 9 月

兩個范圍內重疊天數的通用公式是

MAX(MIN(end1, end2) - MAX(start1, start2) + 1, 0)

在您的情況下,您有一組開始和結束日期,您必須使用datefrompartseomonth從給定的月份和年份構造另一eomonth

不幸的是,SQL Server 不像 MySQL 和 Oracle 那樣支持LEASTGREATEST公式,因此實現起來有點痛苦。 下面是一個使用變量的例子:

declare @month int;
declare @year int;
declare @startDate date;
declare @endDate date;
declare @startOfMonth date;
declare @endOfMonth date;
declare @minEnd date;
declare @maxStart date;
set @month = 1;
set @year = 2020;
set @startDate = '2019-11-12';
set @endDate = '2020-01-13';
set @startOfMonth = datefromparts(@year, @month, 1)
set @endOfMonth = eomonth(@startOfMonth)
set @minEnd = case when @endDate < @endOfMonth then @endDate
                   else @endOfMonth
              end;
set @maxStart = case when @startDate < @startOfMonth then @startOfMonth
                     else @startDate
                end;
select case when datediff(day, @maxStart, @minEnd) + 1 < 0 then 0
            else datediff(day, @maxStart, @minEnd) + 1
       end as days_in_month

輸出:

13

dbfiddle 上的演示 這包括其他示例日期范圍。

如果值來自表,您可以使用一系列 CTE 來實現類似的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM