获取sql

时间:2017-10-16 05:03:00

标签: sql sql-server

如何列出下表中两个日期之间的日期

查询

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  

我试图使用以下查询获得所需的输出,但它不起作用

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

2 个答案:

答案 0 :(得分:1)

最简单的方法是创建一个数字表或使用子查询或CTE获取数字列表,然后根据假期的开始和结束日期将您的假期表加入到该表中。

例如,

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;

答案 1 :(得分: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