检查每月最后三天的当前日期

时间:2012-08-03 20:19:01

标签: sql-server oracle

我想查看当前日期,如果它等于一个月的最后三天,不包括星期六和星期日......

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

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

我不知道如何检查getdate()一个月的最后三天,不包括星期六和星期日..

会有很大的帮助.. 感谢

2 个答案:

答案 0 :(得分: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;

如果今天不在这三天内,这将不会产生任何结果。

答案 1 :(得分:0)

这也是一个月的最后三天,不包括星期六和星期日

SELECT LastFriDay,LastFriDay-1 LastThursday,LastFriDay-2 LastWednesday   FROM( SELECT DATEADD(mm,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(mm,1,GETDATE() - DAY(GETDATE())+ 1)-3 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+ 1)-4 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+ 1)-5 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+ 1)-6 AS LastFriDay UNION ALL SELECT DATEADD(mm,1,GETDATE() - DAY(GETDATE())+ 1)-7 AS LastFriDay )AS YourFridayTable DATENAME(WeekDay,LastFriDay)='星期五'