在SQL Server中填写上一个日期的缺少日期

时间:2017-05-12 06:22:36

标签: sql sql-server-2008 tsql sql-server-2012

如何用sql server中以前的日期相关数据填充缺失日期相关数据?

table:\ temp

CREATE TABLE [dbo].[emp](
    [empid] [int] NULL,
    [doj] [date] NULL,
    [deptid] [int] NULL,
    [ename] [varchar](50) NULL,
    [sal] [int] NULL
) 
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (1, CAST(N'2017-01-02' AS Date), 10, N'ravi', 100)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (1, CAST(N'2017-01-05' AS Date), 10, N'ravi', 200)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (2, CAST(N'2017-01-08' AS Date), 20, N'banu', 300)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (2, CAST(N'2017-01-07' AS Date), 20, N'banu', 250)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (3, CAST(N'2017-01-10' AS Date), 30, N'jai', 400)
GO

根据以上数据,我想要下面的数据

empid   |doj        |deptid   |ename    |sal
    1   |2017-01-02 |10       |ravi     |100
    1   |2017-01-03 |10       |ravi     |100-----missing dates required
    1   |2017-01-04 |10       |ravi     |100-----missing dates required
    1   |2017-01-05 |10       |ravi     |200
    1   |2017-01-06 |10       |ravi     |200-----missing dates required
    2   |2017-01-07 |20       |banu     |250
    2   |2017-01-08 |20       |banu     |300
    2   |2017-01-09 |20       |banu     |300-----missing dates required
    3   |2017-01-10 |30       |jai      |400

如何编写查询以在SQL Server中实现此任务?

1 个答案:

答案 0 :(得分:0)

您可以使用递归CTE。 (如果会有更多行,请使用maxrecursion选项:))

CREATE TABLE [dbo].[emp](
    [empid] [int] NULL,
    [doj] [date] NULL,
    [deptid] [int] NULL,
    [ename] [varchar](50) NULL,
    [sal] [int] NULL
) 
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (1, CAST(N'2017-01-02' AS Date), 10, N'ravi', 100)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (1, CAST(N'2017-01-05' AS Date), 10, N'ravi', 200)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (2, CAST(N'2017-01-08' AS Date), 20, N'banu', 300)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (2, CAST(N'2017-01-07' AS Date), 20, N'banu', 250)
GO
INSERT [dbo].[emp] ([empid], [doj], [deptid], [ename], [sal]) VALUES (3, CAST(N'2017-01-10' AS Date), 30, N'jai', 400)
GO   

IF OBJECT_ID('tempdb..#tmp') IS NOT NULL DROP TABLE #tmp
SELECT * , ROW_NUMBER() OVER (ORDER BY doj) RN
INTO #tmp
FROM dbo.emp    

;WITH CTE AS (
             SELECT empid, deptid,ename,sal, doj,RN
             FROM #tmp
             UNION ALL 
             SELECT a.empid, a.deptid,a.ename,a.sal, DATEADD(DAY,+1,a.doj),a.RN
             FROM CTE a
             JOIN #tmp b ON a.RN+1 = b.RN
             WHERE DATEADD(DAY,+1,a.doj) != b.doj
             )

SELECT * 
FROM CTE
ORDER BY CTE.doj