所以我需要在某个日期添加一些日期,比方说30,但30天不能是日历日,它们是依赖于某些逻辑背后的参数,所以,我需要找到一种方法来添加例如,星期一和星期三之间的30天日期: 如果我在2月15日加30(星期一到星期日),我应该在4月26日 如果我在2月15日之前添加30天(太阳到星期五),那么我应该在3月17日之前获得
如果情况不够明确,请告诉我蚂蚁,我会尽力给出更好的解释。
感谢。
答案 0 :(得分:1)
我会用递归CTE来做,像这样:
-- set datefirst as Sunday. You may need to adjust it ot the correct Datefirst value for your locale
SET DATEFIRST 7
declare @d datetime
set @d = '2017-02-15'
SELECT @d
;with
days as(
-- this CTE where you define the active days. The days start
select 1 as d, 0 as active -- sunday
union
select 2 as d, 1 as active -- monday
union
select 3 as d, 1 as active
union
select 4 as d, 1 as active
union
select 5 as d, 0 as active
union
select 6 as d, 0 as active
union
select 7 as d, 0 as active -- saturday
),
n as (
select CASE WHEN DATEPART(dw, DATEADD(d, 1, @d)) IN (select d from days where active=1) THEN 1 ELSE 0 END as n, @d as dt
union all
select CASE WHEN DATEPART(dw, DATEADD(d, 1, dt)) IN (select d from days where active=1) THEN n+1 else n end, DATEADD(d, 1, dt)
from n where n < 30)
--SELECT * from n order by n
SELECT top 1 @d = dt from n order by n desc
select @d
以上查询适用于周一至周三。使其成为Sun-Friday修改CTE日期中的活动标志
答案 1 :(得分:1)
首先,我在StartDate和EndDate之间生成了一系列日期,但它会返回星期几:
SELECT DATEPART(weekday, DATEADD(DAY, nbr - 1, @StartDate)) as dow
FROM (SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
)nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
然后你可以使用一个简单的WHERE IN()来选择你想要包含的星期几,并计算返回的天数。
DECLARE @StartDate DATE = '20170101'
, @EndDate DATE = '20170131'
SELECT COUNT(*) AS DAYS
FROM (
SELECT DATEPART(weekday, DATEADD(DAY, nbr - 1, @StartDate)) as dow
FROM (SELECT ROW_NUMBER() OVER ( ORDER BY c.object_id ) AS Nbr
FROM sys.columns c
)nbrs
WHERE nbr - 1 <= DATEDIFF(DAY, @StartDate, @EndDate)
) T1
WHERE DOW IN (3,4,5);
在SQL Server中处理一周中的第一天,您可以使用SET DATEFIRST进行更改。