我试图在给定日期之前得到日期差异,不包括工作日。
这就是我所拥有的:
SELECT DATEADD (w, -4, GETDATE())
这将返回 2013-05-04 19:01:53.170 ,这意味着它也会计算周末。
相同
SELECT DATEADD (dw, -4, GETDATE())
任何帮助将不胜感激。
提前致谢。
答案 0 :(得分:3)
我正在使用这些函数返回两个日期之间的非周末秒:
CREATE FUNCTION [dbo].[DateDiff_NoWeekends](
@date1 DATETIME,
@date2 DATETIME
)
RETURNS INT AS BEGIN
DECLARE @retValue INT
SET @date1 = dbo.__CorrectDate(@date1, 1)
SET @date2 = dbo.__CorrectDate(@date2, 0)
IF (@date1 >= @date2)
SET @retValue = 0
ELSE BEGIN
DECLARE @days INT, @weekday INT
SET @days = DATEDIFF(d, @date1, @date2)
SET @weekday = DATEPART(dw, @date1) - 1
SET @retValue = DATEDIFF(s, @date1, @date2) - 2 * 24 * 3600 * ((@days + @weekday) / 7)
END
RETURN @retValue
END
GO
CREATE FUNCTION [dbo].[__CorrectDate](
@date DATETIME,
@forward INT
)
RETURNS DATETIME AS BEGIN
IF (DATEPART(dw, @date) > 5) BEGIN
IF (@forward = 1) BEGIN
SET @date = @date + (8 - DATEPART(dw, @date))
SET @date = DateAdd(Hour, (8 - DatePart(Hour, @date)), @date)
END ELSE BEGIN
SET @date = @date - (DATEPART(dw, @date)- 5)
SET @date = DateAdd(Hour, (18 - DatePart(Hour, @date)), @date)
END
SET @date = DateAdd(Minute, -DatePart(Minute, @date), @date)
SET @date = DateAdd(Second, -DatePart(Second, @date), @date)
END
RETURN @date
END
这是四月(22)所有非周末日的sql-fiddle demo。
SELECT [no weekend days in april] =
(dbo.DateDiff_NoWeekends('2013-04-01','2013-05-01')
/ 3600 / 24)
答案 1 :(得分:1)
下面的查询仅给出了工作日的差异,即计算两天之间的无天数并减去周末天数,
DECLARE @StartDate DATETIME,
@EndDate DATETIME
SELECT @StartDate = '01-July-2008',
@EndDate = '30-July-2008'
;WITH DATE (Date1)
AS (
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', @StartDate), '19000101')
UNION ALL
SELECT DATEADD(DAY, 1, Date1)
FROM DATE
WHERE Date1 < @EndDate
)
SELECT count(*) -
(
SELECT count(*)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) in ('Saturday','Sunday')
)
--CONVERT(VARCHAR(15),d1.DATE1 ,110) as [Working Date],
--DATENAME(weekday, d1.Date1) [Working Day]
from DATE d1 where (DATENAME(weekday, d1.Date1)) not in ('Saturday','Sunday')
请告知我任何澄清
答案 2 :(得分:0)
也许我仍然缺少一些完整的测试,但这也适用于我:在几天内采取差异,然后在每个周末减去2天
DateDiff(d, d1, d2) - 2*DateDiff(wk, d1, d2)
也可以放入一个函数