我想计算一个月的周数,我想计算周数,无论是奇数还是每周,我怎样才能在TSQL中得到它? 谢谢大家!
答案 0 :(得分:7)
这将为您提供当月@dt的一周。第二列在表达式上使用CASE语句,以显示“奇数”或“偶数”
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
答案 1 :(得分:4)
它将为您提供每月的周数
declare @dates datetime
select @dates='2011-03-22'
SELECT datepart(dd,@dates), ceiling (cast(datepart(dd,@dates)as numeric(38,8))/7)
答案 2 :(得分: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;
答案 3 :(得分: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
答案 4 :(得分: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有一个CONCAT函数,可用于更轻松地构建DayOne字符串:
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]