2014-09-30 207 views
0

我有一個日曆表,用於存儲日期行以及該日期是假日還是工作日的指示。TSQL日曆表,從日期開始算起10個工作日

如何選擇即5個工作日內到從2014-12-22將來的日期,以便選定的日期將是2014-12-31

Date_Id  Date_Date Date_JDE Is_WorkingDay 
20141222 2014-12-22 114356  1 
20141223 2014-12-23 114357  1 
20141224 2014-12-24 114358  1 
20141225 2014-12-25 114359  0 
20141226 2014-12-26 114360  0 
20141227 2014-12-27 114361  0 
20141228 2014-12-28 114362  0 
20141229 2014-12-29 114363  1 
20141230 2014-12-30 114364  1 
20141231 2014-12-31 114365  1 
+0

我與** ** 5個工作日內答覆因爲這是t他質疑價值,但你在標題中有** 10 **。 – christiandev 2014-09-30 10:03:23

回答

2

可以使用CTE這樣的...

;WITH cteWorkingDays AS 
(
SELECT Date_Date, ROW_NUMBER() OVER (ORDER BY Date_Date) as 'rowNum' 
FROM TableName 
WHERE Is_WorkingDay = 1 
and Date_Date > '20141222' -- this will be a param I suppose 
) 

SELECT Date_Date 
FROM cteWorkingDays 
WHERE rowNum = 5 -- this can be changed to 10 (title value 

這是手工輸入,但它會足夠接近。

編輯:根據評論。

Declare @DateToUse TYPE -- unsure if you're using a string or a date type. 
SELECT @DateToUse = Date_Date 
    FROM cteWorkingDays 
    WHERE rowNum = 5 
+0

感謝您的回答,真的很有幫助。但是,我怎樣才能從'cteWorkingDays'中選​​擇值到一個變量? – user667430 2014-09-30 10:09:03

+0

我剛剛添加了一個更新,讓我知道如果它沒有意義。 – christiandev 2014-09-30 10:12:18

+1

哦,我看到了,我試圖使用'SET'來設置變量而不是'SELECT'。謝謝。 – user667430 2014-09-30 10:13:00

1
...; 

WITH DatesCTE AS 
(
    SELECT Date_Id, 
      Date_Date, 
      Date_JDE, 
      Is_WorkingDay, 
      ROW_NUMBER() OVER(ORDER BY Date_Date) AS rn 
    FROM DatesTable 
    WHERE Is_WorkingDay = 1 
      AND Date_Date > '2014-12-22' 
) 
SELECT Date_Date 
FROM DatesCTE 
WHERE rn = 5 

SQL Fiddle Demo

0

你可以嘗試這樣的:

with calender as 
(select top 5 date_id,date_date,date_jde from calender 
where date_date>='2014-12-22' and is_workingday='1)calender 
select top 1 * from calender order by date_date desc 
+0

前5名的訂單是多少?你不想包括第二十二? '=>' – christiandev 2014-09-30 10:05:14

+0

您能否請檢查併發佈一個sql小提琴來驗證這個概念? – Aditya 2014-09-30 10:11:50

0

與派生表

select * from 
(
SELECT Date_Date, ROW_NUMBER() OVER (ORDER BY Date_Date) as 'RowNum' 
FROM Table_calendar 
WHERE Is_WorkingDay = 1 
and CAST(Date_Date as DATE) > '2014-12-22' 
)d 
where d.RowNum=5