我正在尝试获取一个月中两个日期之间的天数。因此理想情况下,它看起来像
Month | Days
Jan | 5
Feb | 28
March | 5
日期需要来自一个像这样的表-
Name | Age | Address | AddressStartDate| AddressEndDate
Steve| 19 | randomAdd | 2018-01-26 | 2018-03-05
Steve| 21 | randomAdd | 2018-01-26 | 2018-03-05
我遇到的问题是我可以在该表中有多个具有相同开始日期和结束日期的步骤。
理想情况下,我不想创建日历表,而是使用-
找到了解决此问题的方法Declare @dtFrom date
Declare @dtTo date
select @dtFrom = 2018-01-26
,@dtTo = 2018-03-05
select
year(dt) [Year], month(dt) [Month],
count(*)
from
(
select top(datediff(d, @dtFrom, @dtTo)) dateadd(d, row_number() over
(order by (select null)), @dtFrom) dt
from sys.columns) q
group by year(dt), month(dt
)
order by [Year], [Month]
但是我无法弄清楚如何将它们分开。无论如何,我可以在一张桌子上拿到这些吗?
我目前大约有1500行,我需要重现此数据!
答案 0 :(得分:2)
您走在正确的道路上,只需要使用CROSS APPLY
示例
Declare @YourTable Table ([Name] varchar(50),[Age] int,[Address] varchar(50),[AddressStartDate] date,[AddressEndDate] date)
Insert Into @YourTable Values
('Steve',19,'randomAdd','2018-01-26','2018-03-05')
,('Steve',21,'randomAdd','2018-01-26','2018-03-05')
Select A.*
,B.*
From @YourTable A
Cross Apply (
Select Month=DateName(MONTH,D)
,Days = count(*)
From (
Select Top (DateDiff(DAY,[AddressStartDate],[AddressEndDate])+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[AddressStartDate])
From master..spt_values n1,master..spt_values n2
) B1
Group By Year(D),DateName(MONTH,D)
) B
返回
编辑-更新为NULL结束日期
Select A.*
,B.*
From @YourTable A
Cross Apply (
Select Month=DateName(MONTH,D)
,Days = count(*)
From (
Select Top (DateDiff(DAY,[AddressStartDate],IsNull([AddressEndDate],GetDate()))+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[AddressStartDate])
From master..spt_values n1,master..spt_values n2
) B1
Group By Year(D),DateName(MONTH,D)
) B
最终编辑-连续一年到一个月
Select A.*
,B.*
From @YourTable A
Cross Apply (
Select Month=concat(DateName(MONTH,D),'-',year(D))
,Days = count(*)
From (
Select Top (DateDiff(DAY,[AddressStartDate],IsNull([AddressEndDate],GetDate()))+1) D=DateAdd(DAY,-1+Row_Number() Over (Order By (Select Null)),[AddressStartDate])
From master..spt_values n1,master..spt_values n2
) B1
Group By Year(D),DateName(MONTH,D)
) B