[英]SQL Server : get date range and number of days
I have 4 columns (two columns filter) and one column date and one column flag.我有 4 列(两列过滤器)和一列日期和一列标志。 For a combination of column 1 and column 2, and the open flag, I want to find the open date, the close date and number of days where it was open.
对于第 1 列和第 2 列以及打开标志的组合,我想找到打开日期、关闭日期和打开的天数。
Here is my example and what I want to find with SQL is with the blue/grey color这是我的例子,我想用 SQL 找到的是蓝色/灰色
如果您已经有两个可用的日期作为OpenDate
和CloseDate
在您的情况下,您可以使用DATEDIFF()
函数,如下所示。
Select DATEDIFF(DAY, OpenDate, CloseDate) as NumberOfOpenDays from YourTable
This looks a gaps-and-islands problem -- but the islands are already defined by opendt
(and perhaps col1
and col2
).这看起来是一个间隙和岛屿问题——但这些岛屿已经由
opendt
(可能还有col1
和col2
)定义。
So, you can just use row_number()
:所以,你可以只使用
row_number()
:
select row_number() over (partition by col1, col2, opendt order by effectivedt)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.