我在SQL Server中有表格如图所示 - 如何获得所需的输出?

时间:2017-01-17 02:58:10

标签: sql sql-server

我有桌子

Date1      | Date2       | Days
-------------------------------
2017-01-25   2017-02-03     8

如何将其转换为这样的输出:

Periode | Days
--------------
January    5
February   3

1 个答案:

答案 0 :(得分:2)

以下是根据两列的值生成给定时间段内工作日计数的一种方法,使用CROSS APPLY生成非工作日的日期,然后按{{1}进行分组每个日期的月份。

DATENAME

修改

根据有关此处实际需求的评论,您可以根据DECLARE @TABLE TABLE (Date1 DATE, Date2 DATE); -- Days field doesn't matter. INSERT @TABLE(Date1, Date2) VALUES ('2017-01-25', '2017-02-03'); WITH CTE1(N) AS (SELECT 1 FROM (VALUES (1), (1), (1), (1), (1), (1), (1), (1), (1), (1)) A(B)), CTE2(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 FROM CTE1 A CROSS JOIN CTE1 B CROSS JOIN CTE1) -- Generate numbers 0-999. SELECT Periode = DATENAME(MONTH, D.Dates), Days = COUNT(*) FROM @TABLE T CROSS APPLY ( SELECT Dates = DATEADD(DAY, C.N, T.Date1) FROM CTE2 C WHERE C.N <= DATEDIFF(DAY, T.Date1, T.Date2) -- Generate all dates between Date1 and Date2. AND DATEPART(WEEKDAY, DATEADD(DAY, C.N, T.Date1)) NOT IN (1, 7) -- Where the day isn't Saturday/Sunday. ) D GROUP BY DATENAME(MONTH, D.Dates), DATEPART(MONTH, D.Dates) ORDER BY DATEPART(MONTH, D.Dates) ; 列计算一个月内的实际天数:

DATETIME

根据样本数据,1月份产生6.375天(6天全天加25小时9小时)和2月份2.125天(2天全天加3小时3天),共计8.5天。