【问题标题】:How to get the ISOweek and the start and end date of each every week in the whole year using sql server如何使用sql server获取全年每个星期的ISOweek和开始和结束日期
【发布时间】:2015-04-21 04:24:43
【问题描述】:

我想获取一年中从 1 月 1 日到第 52 周的完整 ISOweek。

我想每周获取开始日期和结束日期。

我有我的脚本,但我没有得到我想要的输出

脚本:

Declare @starttime datetime
Declare @endtime datetime
Set @starttime = '2015-01-01 10:50:29.293'
Set @endtime = '2015-12-31 10:50:29.293'

declare @time datetime
while @endtime > @starttime
begin

print DATEPART(Week,@starttime)
print @starttime
set @time = DATEADD(DAY, 6,@starttime)
 If @time<@endtime
Begin

    print @time
    print DATEPART(Week,@time)

    set @starttime = DATEADD(DAY, 1,@time) 
End
Else
begin
    print @endtime
    print DATEPART(Week,@endtime)
     set @endtime = @starttime
End
end

输出:

1 --> this is the week of the @Starttime
Jan  1 2015 10:50AM -->@starttime
Jan  7 2015 10:50AM -->@endtime
2 --> this is the week of the endtime 

.......

51
Dec 17 2015 10:50AM
Dec 23 2015 10:50AM
52
52
Dec 24 2015 10:50AM
Dec 30 2015 10:50AM
53

到年底。

我希望我的输出是这样的

示例:

1 --> this is the week of the @Starttime
Jan  1 2015 10:50AM -->@starttime
Jan  3 2015 10:50AM -->@endtime
1 --> this is the week of the @endtime

我希望我的开始时间是我一周的第一个日期,我的结束时间是一周的最后一个日期,直到年底。

你能帮我解决这个问题吗?

【问题讨论】:

    标签: sql sql-server sql-server-2008 date datetime


    【解决方案1】:

    您可以使用 DATEPARTWEEKDAY 来获取星期几,然后使用递归 CTE 来获取随后的几周。像这样的

    DECLARE @dtstart DATETIME= '20150101'
    DECLARE @dtend DATETIME= '20151231'
    
    ;WITH CTE AS 
    (
    SELECT 1 as WeekNo, @dtstart weekstart,DATEADD(d,6-DATEPART(WEEKDAY,@dtstart),@dtstart) weekend
    UNION ALL
    SELECT CTE.WeekNo + 1 as WeekNo, DATEADD(d,1,CTE.weekend),CASE WHEN  DATEADD(d,7,CTE.weekend) < @dtend THEN DATEADD(d,7,CTE.weekend) ELSE @dtend END
    FROM CTE WHERE DATEADD(d,1,CTE.weekend) < @dtend
    )
    SELECT * FROM CTE;
    

    【讨论】:

    • 感谢先生的想法。上帝保佑:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2022-01-07
    • 2016-10-18
    相关资源
    最近更新 更多