SQL Server扩展表并在日期范围内为每一行添加日期

时间:2019-02-24 14:12:35

标签: sql sql-server

我有一张这样的桌子:

Id user
-------
1  A
2  B

我想扩展它,并为每行添加日期,如下所示:

Id user date
------------------
1  A    20190101
1  A    20190102
2  B    20190101
2  B    20190102

4 个答案:

答案 0 :(得分:1)

带有日历表的简单交叉联接应该在这里起作用:

WITH dates AS (
    SELECT '20190101' AS dt UNION ALL
    SELECT '20190102'
)

SELECT
    t.Id,
    t.user,
    d.dt AS date
FROM yourTable t
CROSS JOIN dates d;

答案 1 :(得分:0)

您可以使用横向连接。在SQL Server中,这使用cross apply语法:

select t.*, v.dte
from t cross apply
     (values (convert(date, '2019-01-01')) (convert(date, '2019-01-02'))
     ) v(dte);

答案 2 :(得分:0)

感谢蒂姆的回应,我有个主意:

    WITH thedates AS
    (
        SELECT CAST(@startdate AS DATETIME) AS thedates
            UNION ALL
        SELECT DATEADD(DAY,1,thedates)
        FROM thedates
        WHERE DATEADD(DAY,1,thedates)<= CAST(@enddate AS DATETIME)
    )

    SELECT t.user_id,t.user_name,CONVERT(NVARCHAR(10),d.thedates,112)
    FROM [dbo].[test] t
    CROSS JOIN thedates d

答案 3 :(得分:0)

请尝试以下操作:

DECLARE @FromDate DATE = '2019-01-01', @ToDate DATE = '2019-01-02';

;WITH rs AS (SELECT @FromDate dt UNION ALL SELECT DATEADD(DAY,1,dt) FROM rs WHERE dt<@ToDate)
SELECT t.Id,t.[user],rs.dt AS [date]
FROM [YourTableName] t
CROSS APPLY rs 
ORDER BY t.[user],rs.dt
OPTION (MaxRecursion 0)
;