2016-05-20 20 views

回答

1
declare @MonthStart datetime 
-- Find first day of current month 
set @MonthStart = dateadd(mm,datediff(mm,0,getdate()),0) 

select 
    Week, 
    WeekStart = dateadd(dd,(Week-1)*7,@MonthStart) 
from 
    (-- Week numbers 
    select Week = 1 union all select 2 union all 
    select 3 union all select 4 union all select 5 
    ) a 
where 
    -- Necessary to limit to 4 weeks for Feb in non-leap year 
    datepart(mm,dateadd(dd,(Week-1)*7,@MonthStart)) = 
    datepart(mm,@MonthStart) 

得到了在鏈接的答案:http://www.sqlservercentral.com/Forums/Topic1328013-391-1.aspx

0

這裏是接近的方式之一:

一月最少有29天或以上,最多不超過31天。意思是每個月幾乎總是5個星期,除非是非閏年的feburary,在這些情況下,每個月是4個星期。

你可以參考這個來找出哪些年份是「飛躍」。 Check for leap year

希望這有助於!

0

下面的代碼可以讓你選擇一個開始和結束日期,並且每週輸出一行,編號星期,這些日期間:

declare @start date = '1/1/2016' 
declare @end date = '5/1/2016' 

;with cte as (select @start date 
        , datename(month, @start) as month 
       union all 
       select dateadd(dd, 7, date) 
       , datename(month, dateadd(dd, 7, date)) 
       from CTE 
       where date <= @end 
      ) 

select *, 'week ' 
    + cast(row_number() over (partition by month order by date) as varchar(1)) 
from CTE 
order by date 
相關問題