没有周末的两个日期列之间的Datediff,添加为EXTRA列

时间:2017-12-12 19:50:01

标签: sql sql-server sql-server-2008

我的表中有两个日期列。我想添加一个额外的列,其中包含两个日期字段之间的天数而没有周末。

dbo.Date:

+------------+------------+-------------+
|   Date1    |   Date2    | DaysBetween |
+------------+------------+-------------+
| 2017-12-01 | 2017-12-31 |          21 |
+------------+------------+-------------+

所以周末被排除在这个结果之外。

1 个答案:

答案 0 :(得分:0)

试试这个:

使用CTE

DECLARE @st_date date,
        @end_date date

SET @st_date = '12/01/2017'
SET @end_date = '12/31/2017'

;WITH dateCte
AS (SELECT
  @st_date AS [days]
UNION ALL
SELECT
  DATEADD(D, 1, [days]) [days]
FROM dateCte
WHERE [days] < @end_date)
SELECT
  @st_date Date1,
  @end_date Date2,
  COUNT(DATENAME(WEEKDAY, days)) [DaysBetween]
FROM dateCte
WHERE DATENAME(WEEKDAY, days) <> 'Saturday'
AND DATENAME(WEEKDAY, days) <> 'Sunday'