在数据库表中显示每月的最后一个工作日。 (工作日不包括周六,周日)

时间:2019-08-05 20:07:58

标签: sql-server tsql

我想在数据库表中显示每月的最后一个工作日(不包括星期六,星期日)。

3 个答案:

答案 0 :(得分:0)

我们使用pgadmin,我猜它类似于SQL Server,这是我们使用的查询:

Eq (Integer -> Integer -> Integer)

Maybe包含您知道您放假的日子,例如假期,而bolReturn = true; --Get the day of week SELECT EXTRACT(DOW FROM _start) Into dayofweek; --Sataurday if dayofweek = 6 then bolReturn = false; --Sunday ELSIF dayofweek = 0 then bolReturn = false; end if; --Check against office closing select count(*) as start into intCount from tables.officeclosed where closeddate = _start; if intCount > 0 then bolReturn = false; end if; return 是您传递的日期。

答案 1 :(得分:0)

尝试一下:

create function dbo.LastBusinessDayOfMonth ( @Date date )
returns date as
begin
  declare @Result date;
  -- Find last day of the month
  set @Result = EOMONTH(@Date);
  -- If this date is Saturday or Sunday, 
  -- choose the preceding date
  while DATEDIFF(day,'0001-01-01',@Result)%7 >= 5
    set @Result = DATEADD(day,-1,@Result)
  return @Result;
end

答案 2 :(得分:0)

肯定需要更多信息,正如肖恩(Sean)所说,您需要考虑公共假期等。

以下使用从子查询中选择3个日期的“ TOP 1”与交叉应用。

SET DATEFIRST 1

select *
from
(
  SELECT Months.Idx, EOMONTH(datefromparts(year(getdate()), Months.idx, 1)) as EOMDate
  FROM ( VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12) ) Months(Idx)
) Months
cross apply ( 
    select top 1 mldx.date AS LastBusinessDay
    from
    (
          select Months.EOMDate date
          union all select dateadd(day, -1, Months.EOMDate )
          union all select dateadd(day, -2, Months.EOMDate )
      ) mldx
    where datepart(weekday, mldx.date ) <= 5
    order by mldx.date desc
  ) lastBusinessDay