2017-02-15 72 views
0

所以我需要添加一些日期,比如說30,但30天不能是日曆天,它們是依賴於某些邏輯的參數,所以我需要找到一種方法來添加日期之間星期三和星期三之間的30天,例如: 如果我添加30(星期三到星期三)到2月15日,我應該得到4月26日 如果我添加30(太陽到星期五) 15日,我應該得到3月17日SQL server DATEADD特定的週日

如果情況不夠清楚,讓我知道螞蟻我會盡力給出一個更好的解釋。

謝謝。

+0

您的意思是工作日? – McNets

+0

@McNets很好,有點,但不僅工作日,它可能是星期五到星期五,星期一到星期二......它變化很大,但如果有一種方法可以定義工作日在每個查詢中需要的日子,我可以與該工作 – rhernandez

+0

你有一個查找日曆表? – McNets

回答

1

我第一次產生了一系列的起始日期和結束日期之間的日期,但它返回星期幾:

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改變它。

請在此檢查:http://rextester.com/WCLIXM28868

+0

看起來不錯!將嘗試它並讓你知道! – rhernandez

+0

太棒了!這正是我所期待的,是快速而容易理解的。謝謝! – rhernandez

+0

我很高興能夠提供幫助。 – McNets

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 

以上查詢是週一至週三爲了讓孫週五修改的有效標誌在天CTE

+0

這可能工作,因爲我得到的天數(0 =星期日,7 =星期六),我可以使用CASE當......在CTE,我會嘗試這種方法。謝謝! – rhernandez

+0

這個效果很好,但是生產速度可能會很慢 – rhernandez

相關問題