这是我的问题:
CREATE FUNCTION dbo.ufn_LastBusinessDayOfMonth (@Dt datetime)
RETURNS datetime
AS
BEGIN
DECLARE @dt2 datetime
DECLARE @Df int
DECLARE @dSat int
DECLARE @dSun int
SELECT
@dt2 = DATEADD(D, -1, DATEADD(m, 1 + DATEDIFF(m, 0, @Dt), 0))
SELECT
@dSat = DATEPART(dw, '2018-01-06') -- Known Saturday
SELECT
@dSun = (@dSat % 7) + 1
SELECT
@dt2 = (
CASE
WHEN DATEPART(dw, @dt2) = @dSun THEN DATEADD(DAY, -2, @dt2)
WHEN DATEPART(dw, @dt2) = @dSat THEN DATEADD(DAY, -1, @dt2)
ELSE @dt2
END)
RETURN @dt2
END
答案 0 :(得分:0)
DECLARE @Dt datetime
SET @Dt = '03/21/2018'
DECLARE @lastOfMonth datetime, @3DaysBeforeTheEnd DATETIME
set @lastOfMonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@Dt)+1,0))
SET @3DaysBeforeTheEnd = DATEADD(d,-2,@lastOfMonth)
select top 1 DATENAME(weekday, x.[Date]), x.[Date]
from (
SELECT TOP (DATEDIFF(DAY, @3DaysBeforeTheEnd, @lastOfMonth) + 1)
[Date] = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @3DaysBeforeTheEnd)
FROM sys.all_objects a
CROSS JOIN sys.all_objects b
)x
WHERE DATENAME(weekday, x.[Date]) NOT IN ('Saturday','sunday')
order by x.[Date] desc