2017-10-16 156 views
2

我怎樣才能在下面的表獲取SQL兩個日期之間的日期列表

查詢

select * from Vacation 

輸出

EmpID VStart  VacEnd  VacType  PostDate 
362330 2017-10-15 2017-10-19 Sick Leave 2017-10-15 

列出兩個日期之間的日期所需輸出

EmpID Date  VacType  
362330 2017-10-15 Sick Leave 
362330 2017-10-16 Sick Leave 
362330 2017-10-17 Sick Leave 
362330 2017-10-18 Sick Leave 
362330 2017-10-19 Sick Leave 

我曾嘗試使用下面的查詢以獲得所需的輸出,但它沒有工作,要做到這一點是創建一個數字表或使用子查詢或CTE得到

DECLARE @Start DATETIME, @End DATETIME 
SELECT @Start='2017-10-15' , @End = '2017-10-19' 
;WITH DateList 
AS 
(
SELECT @Start [Date] 
UNION ALL 
SELECT [Date] +1 FROM DateList WHERE [Date] <@End 
) 
SELECT dbo.Vacation.EmpID,[Date], dbo.Vacation.VacType FROM dbo.Vacation INNER JOIN DateList ON DateList.Date = dbo.Vacation.VStart 
+1

爲什麼你已經在列中已經有了這些值的時候聲明瞭「@ Start」和「@ End」? –

回答

1

最簡單的方法一個數字列表,然後根據休假的開始和結束日期加入您的休假表。

例如,

DECLARE @Vacation TABLE (EmpID INT, VStart DATE, VacEnd DATE, VacType VARCHAR(255)); 
INSERT @Vacation (EmpID, VStart, VacEnd, VacType) VALUES 
(1, '2017-10-15', '2017-10-19', 'Sick Leave'), 
(2, '2017-10-15', '2017-10-16', 'Super Fun Happy Vacation'); 

SELECT Vacation.EmpID, 
     [Date] = DATEADD(DAY, T.N, Vacation.VStart), 
     Vacation.VacType 
FROM (
    SELECT N = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 
    FROM sys.objects 
) AS T 
JOIN @Vacation AS Vacation 
    ON DATEDIFF(DAY, Vacation.VStart, Vacation.VacEnd) >= T.N; 
0

我剛纔所作變化不大,在查詢中,我沒有測試過,但似乎它會工作,請嘗試。

DECLARE @Start DATETIME, @End DATETIME 
SELECT @Start='2017-10-15' , @End = '2017-10-19' 
;WITH DateList 
AS 
(
SELECT @Start AS [Date],@Start AS StartDate 
UNION ALL 
SELECT [Date] +1, @Start AS StartDate FROM DateList WHERE [Date] <@End 
) 
SELECT dbo.Vacation.EmpID,DateList.[Date], dbo.Vacation.VacType FROM dbo.Vacation INNER JOIN DateList ON DateList.StartDate = dbo.Vacation.VStart 
相關問題