2012-08-03 108 views
0

我要检查当前的日期,如果它等于上个月不包括周六和周日三天......检查当前日期与月份的最后三天

我可以得到一个月的最后一天

SELECT DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) 

我不知道如何检查getdate()与月不包括周六和周日的最后三天..

将有很大的帮助.. 感谢

+1

那不是本月的最后一天。这是本月的最后一秒,如果将它分配给smalldatetime变量,它将会四舍五入,并且如果将它与datetime2进行比较,它可能会丢失数据。为什么这个标记为Oracle? – 2012-08-03 20:25:23

+0

你也可以明确地确认你的意思是“不包括周六和周日”吗?你的意思是如果这个月的最后一天是星期六,你实际上是想包括星期三/星期五/星期五而不是星期四/星期五/星期六? – 2012-08-03 20:32:08

回答

1
-- make sure Sunday is the first day of the week: 
SET DATEFIRST 7; 

DECLARE 
    @today SMALLDATETIME, 
    @nextmonth SMALLDATETIME; 

-- today at midnight is the number of days since 1900-01-01 
-- the first day of nextmonth is one month after the first 
-- day of the current month 
SELECT 
    @today = DATEDIFF(DAY, '19000101', CURRENT_TIMESTAMP), 
    @nextmonth = DATEADD(MONTH, 1, @today-DAY(@today)+1); 

-- so if today is greater than 3 days prior to the first of next month 
-- and today is not a Saturday or a Sunday: 
IF @today >= DATEADD(DAY, -3, @nextmonth) 
    AND DATEPART(WEEKDAY, @today) NOT IN (1,7) 
BEGIN 
    PRINT 'Bazinga!'; 
END 

如果你真正的意思是,你要在这个月的最后三个非周末两天,则:

SET DATEFIRST 7; 

DECLARE 
    @today SMALLDATETIME, 
    @nextmonth SMALLDATETIME; 

SELECT 
    @today = DATEDIFF(DAY, 0, GETDATE()), 
    @nextmonth = DATEADD(MONTH, 1, @today-DAY(@today)+1); 

;WITH x AS 
(
    -- get the 5 days prior to the first day of next month: 
    SELECT TOP (5) d = DATEADD(DAY, -ROW_NUMBER() OVER 
    (ORDER BY [object_id]), @nextmonth) FROM sys.all_objects 
), 
y AS 
(
    -- get the last three days that aren't on Sat/Sun: 
    SELECT TOP (3) d FROM x 
    WHERE DATEPART(WEEKDAY, d) NOT IN (1,7) 
    ORDER BY d DESC 
) 
-- now find out if today is in those three days: 
-- (by definition, today can't be Sat/Sun) 
SELECT 'Bazinga!' FROM y WHERE d = @today; 

这会没有结果,如果今天不是在那三天。

+0

非常感谢..帮助 – user1046415 2012-08-06 15:30:41

0

这也使得本月不包括周六和周日

SELECT LastFriDay,LastFriDay-1 LastThursday,LastFriDay-2 LastWednesday FROM( SELECT DATEADD(毫米,1,GETDATE()的最后三天 - DAY(GETDATE ())+ 1)-1 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+1)-2 AS LastFriDay UNION ALL SELECT DATEADD () - DAY(GETDATE())+1)-3 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+1)-4 AS LastFriDay UNION ALL(mm,1,GETDATE() - DAY(GETDATE())+ 1) - 选择DATEADD(mm,1,GETDATE() - DAY(GETDATE())+ 1)-5 AS LastFriDay UNION ALL 6 AS LastFriDay UNION ALL SELECT DATEADD(毫米,1,GETDATE() - DAY(GETDATE())+ 1)-7 AS LastFriDay )AS YourFridayTable WHERE DATENAME(星期,LastFriDay)= '星期五'

相关问题