gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:01:17 26 4
gpt4 key购买 nike

我正在尝试获取一个月中两个日期之间的天数。所以理想情况下这看起来像

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]

但我不知道如何将它们分开。我可以在一张 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

返回

enter image description here

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

关于sql - 获取 2 个日期之间每月的准确日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787342/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com