2011-02-07 232 views
6

我想計算一個月的週數,我想計算一下它的週數是否在奇數或偶數週我怎樣才能在TSQL中得到這個? 謝謝大家!TSQL計算月份的月份數

+2

列表中的一些樣本日期和預期產出 – RichardTheKiwi 2011-02-07 23:44:54

回答

6

這給你的日起一個月內@dt的一週。有一個使用CASE語句上的表達,顯示無論是「奇」或「偶」第2個欄

declare @dt datetime 
set @dt = GETDATE() 

select 
    WhichWeekOfMonth = datepart(wk, @dt) 
        - datepart(wk,dateadd(m, DATEDIFF(M, 0, @dt), 0)) + 1, 
    case when (datepart(wk, @dt) 
      - datepart(wk,dateadd(m, DATEDIFF(M, 0, @dt), 0)) + 1) % 2 = 1 
     then 'Odd' else 'Even' end 
0

試試這個:

SELECT (DATEPART(d, '02/07/2011')/7)%2 AS WeekNo, --Replace your date column in place of '02/07/2011' 
     CASE (DATEPART(d, '02/07/2011')/7)%2 
       WHEN 1 THEN 'Odd' 
       ELSE 'Even' 
      END AS WeekType 
+0

給出了錯誤的答案(按我的定義 - 見我答案) - 它表示它在第1周 – RichardTheKiwi 2011-02-07 23:47:42

+0

上面的查詢給出了給定的日期是一週中哪一週是偶數週還是奇數週... – Chandu 2011-02-07 23:49:13

4

它會給你一週號每個月

declare @dates datetime 
select @dates='2011-03-22' 
SELECT datepart(dd,@dates), ceiling (cast(datepart(dd,@dates)as numeric(38,8))/7) 
3

怎麼樣東西可讀,輕鬆定製和可預測...

DECLARE @dayOfMonth AS INT; 
SET @dayOfMonth = DATEPART(DAY, '3/14/2013'); 
SELECT CASE 
    WHEN @dayOfMonth < 8 THEN 1 
    WHEN @dayOfMonth < 15 THEN 2 
    WHEN @dayOfMonth < 22 THEN 3 
    ELSE 4 
END AS weekOfMonth; 
0

我認爲這使得該方法非常明顯:

DECLARE @DayOne DATETIME 
DECLARE @ThisDay DATETIME 
SET @ThisDay = GETDATE() 
SET @DayOne = CAST(CAST(MONTH(@ThisDay) AS VARCHAR) + '/1/' + CAST(YEAR(@ThisDay) AS VARCHAR) AS DATETIME) 
SELECT (DATEPART(wk, @ThisDay) - DATEPART(wk, @DayOne) + 1) AS [Week Of Month] 

SQL Server 2012中有一個可以用於更容易建立DayOne字符串CONCAT功能:

DECLARE @DayOne DATETIME 
DECLARE @ThisDay DATETIME 
SET @ThisDay = GETDATE() 
SET @DayOne = CAST(CONCAT(MONTH(@ThisDay), '/1/', YEAR(@ThisDay)) AS DATETIME) 
SELECT (DATEPART(wk, @ThisDay) - DATEPART(wk, @DayOne) + 1) AS [Week Of Month]