在 2 个日期之间每月获取准确的日期值

Getting exact day values per month, between 2 dates

我正在尝试获取一个月中 2 个日期之间的天数。所以这看起来像

Month | Days
 Jan  |  5
 Feb  |  28
March |  5

日期需要来自如下所示的 table -

Name | Age | Address   | AddressStartDate| AddressEndDate 
Steve| 19  | randomAdd | 2018-01-26      | 2018-03-05
Steve| 21  | randomAdd | 2018-01-26      | 2018-03-05

我遇到的问题是我可以在这个 table 中有多个具有完全相同的开始和结束日期的史蒂夫。

理想情况下,我不想制作日历 table,我找到了解决这个问题的方法,方法是使用 -

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]

但我不知道如何将它们分开。无论如何我可以在 1 table 中得到这些吗?

我目前有大约 1500 行,我需要为这些数据重新生成这些数据!

你走在正确的道路上,你只需要使用 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

Returns

EDIT - Updated for NULL EndDate

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

Final Edit -- Concat Year to Month

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