我的表格中有from date
和to date
,我想知道SQL Server 2008中没有星期日的两个日期之间的总天数。
给我一个询问..
接受我的问题......
答案 0 :(得分:2)
好的,所以计算总天数,减去总周数,以及从日期是星期日的情况下的小提琴因素:
SELECT
DATEDIFF(dd, FromDate, ToDate)
-DATEDIFF(wk, FromDate, ToDate)
-(CASE WHEN DATEPART(dw, FromDate) = 1 THEN 1 ELSE 0 END)
答案 1 :(得分:1)
尝试以此为例进行操作..
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'
SELECT
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
答案 2 :(得分:1)
你可以用CTE做到这一点,这个问题很容易变成标量函数:
DECLARE @startDate DATETIME = '2011-09-01'
DECLARE @endDate DATETIME = '2011-09-23'
;WITH DateRange (date) AS
(
SELECT @startDate
UNION ALL
SELECT Date+1
FROM DateRange
WHERE date<@endDate
)
SELECT COUNT(*) FROM DateRange WHERE DATENAME(dw,Date) != 'Sunday'
返回20
,这是本月到目前为止不是星期几的天数。
这是一个可以使用的等效函数:
CREATE FUNCTION dbo.NumberOfDaysExcludingSunday(
@startDate DATETIME,
@endDate DATETIME
) RETURNS INT AS
BEGIN
DECLARE @rtn INT
;WITH DateRange (date) AS
(
SELECT @startDate
UNION ALL
SELECT Date+1
FROM DateRange
WHERE date<@endDate
)
SELECT @rtn = COUNT(*) FROM DateRange WHERE DATENAME(dw,Date) != 'Sunday'
RETURN @rtn
END
用法:
SELECT dbo.NumberOfDaysExcludingSunday(startDate,endDate)
FROM myTable