在两个日期之间,我如何用一个id取所有日期

时间:2018-08-02 15:56:26

标签: sql sql-server

empid   startdate      expirydate
18426   2018-01-01     2018-01-05

我期待着:-

date          id
2018-01-01   18426  
2018-01-02   18426  
2018-01-03   18426  
2018-01-04   18426  
2018-01-05   18426  

2 个答案:

答案 0 :(得分:2)

您需要以递归方式使用cte

with t as (
     select empid, startdate, enddate
     from table
     union all
     select empid, dateadd(day, 1, startdate), enddate
     from t
     where stardate < enddate
)

select *
from t
option (maxrecursion 0);

答案 1 :(得分:1)

使用Calendar TableTally Table

您也可以即时进行。该示例将使您走上正确的道路:

DECLARE @StartDate date, @EndDate date;
SET @StartDate = '20180101';
SET @EndDate = '20190105';

WITH N AS (
    SELECT *
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) V(U)),
Tally AS(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
    FROM N N1
         CROSS JOIN N N2
         CROSS JOIN N N3
         CROSS JOIN N N4)
SELECT DATEADD(DAY, I, @StartDate) AS [date]       
FROM Tally T
WHERE DATEADD(DAY, I, @StartDate) <= @EndDate;