溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在SQL Server計算XX年第XX周是哪幾天

發布時間:2020-08-02 09:51:04 來源:網絡 閱讀:1903 作者:易語隨風去 欄目:關系型數據庫

SQL Server有一個很強大的函數:DATEPART()

它可以計算2017-10-17是屬于今年的

第幾天:select datepart(dy,'2017-10-17')

第幾周:select datepart(wk,'2017-10-17')

第幾月:select datepart(mm,'2017-10-17')

第幾季度:select datepart(qq,'2017-10-17')

一周中的星期幾:select (case datepart(dw,'2017-10-17')

when 1 then 'Sunday'

when 2 then 'Monday'

when 3 then 'Tuesday'

when 4 then 'Wednesday'

when 5 then 'Thursday'

when 6 then 'Friday'

when 7 then 'Saturday'

end)


那么問題來了:如果我們需要知道2017年的第25周是哪幾天,應該怎么編寫SQL


分析:

1. 2017年第25周第1天是幾月幾號

1.1 2017年的第1周的第1天2017-1-1是星期幾

1.2 每周有7天

1.3 2017-1-1需要加上多少天等于2017年第25周第1天

那么,第25周的第1天 = 2017年的第1周天數 + (25-2)*7,25-2即減去第1周和第25周


2、2017年第25周最后1天是幾月幾號

2017年第25周最后1天 = 2017年第25周第1天 + 6天


到了這里,我們知道關鍵的點為如何計算2017第1周的天數,在計算天數時最關鍵的是確定星期日是一周的第1天還是最后一天。


2017年1月1日恰好是星期日

如何在SQL Server計算XX年第XX周是哪幾天

如果星期日是一周的第一天

2017年第25周的第1天 = 2017年1月1日 + 7天 + (25-2)*7天

SQL語句:dateadd(day,7+(25-2)*7,'2017-1-1'),結果為:2017-6-18

2017年第25周為:2017-6-18至2017-6-24


如果星期日是一周的最后一天

2017年第25周的第1天 = 2017年1月1日 + 1天 + (25-2)*7天

SQL語句:dateadd(day,1+(25-2)*7,'2017-1-1'),結果為:2017-6-12

2017年第25周為:2017-6-12至2017-6-18


接下來把上面的計算方式編寫為SQL語句

星期日為第1天:

declare @weekofyear int

declare @date datetime

declare @dayofweek int

declare @firstday varchar(20)

declare @firstweek int

set @date='2017-1-1'

select @dayofweek=datepart(dw,@date)

set @weekofyear=25

set @firstweek=8-@dayofweek

declare @begin_date datetime

declare @end_date datetime

set @begin_date=dateadd(day, @firstweek+(@weekofyear-2)*7,@date)

set @end_date=dateadd(day,6,@begin_date)


星期日為最后一天:

declare @weekofyear int

declare @date datetime

declare @dayofweek int

declare @firstweek int

set @date='2017-1-1'

select @dayofweek=datepart(dw,@date)

set @weekofyear=25

if(9-@dayofweek)>7

begin

set @firstweek=9-@dayofweek-7

end

else

begin

set @firstweek=9-@dayofweek

end

declare @begin_date datetime

declare @end_date datetime

set @begin_date=dateadd(day, @firstweek+(@weekofyear-2)*7,@date)

set @end_date=dateadd(day,6,@begin_date)


再將代碼整合為存儲過程,結果如下:

如何在SQL Server計算XX年第XX周是哪幾天

結果驗證:

如何在SQL Server計算XX年第XX周是哪幾天

如何在SQL Server計算XX年第XX周是哪幾天

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女