简体   繁体   中英

How to populate missing date row with next date row in sql server?

  date  value       
01-01-2020  2       
04-01-2020  3   
05-01-2020  5       
06-01-2020  7       
05-01-2020  9       

I want output:

date    value
01-01-2020  2
02-01-2020  3
03-01-2020  3
04-01-2020  3
05-01-2020  5
06-01-2020  7
07-01-2020  9
08-01-2020  9
09-01-2020  9
10-01-2020  9
WITH cte1 AS 
(
    SELECT *, 
      lead(date) OVER (ORDER BY date) AS NextDate FROM Screen1
) 
SELECT
  c.Date,
  t.value
FROM Calender1 c 
JOIN cte1 t ON c.Date 
  BETWEEN t.date AND ISNULL(DATEADD(day, -1, t.NextDate), t.date)

I have tried this but its duplicating the previous date value.In this query i have used a calender table and joined that table with main table which has missing dates.

First you need to have calendar table. Then you can find the next available value using CROSS APPLY and fill that value.

declare @table table(dateval date, val int)

insert into @table
values 
('2020-01-01',  2),
('2020-01-04',  3 ),  
('2020-01-05',  5 ),      
('2020-01-06',  7 ),      
('2020-01-10',  9)

DECLARE @StartDate DATE = '2020-01-01'
DECLARE @EndDate DATE = '2020-01-31'

;WITH Cal(n) AS
(
SELECT 0 UNION ALL SELECT n + 1 FROM Cal
WHERE n < DATEDIFF(DAY, @StartDate, @EndDate)
),
FnlDt(d) AS
(
SELECT DATEADD(DAY, n, @StartDate) FROM Cal
)


SELECT f.d, t.val
FROM FnlDt as f
CROSS APPLY
(select top 1 val from 
@table as t
where t.dateval >= f.d
order by t.dateval) as t(val)
d val
2020-01-01 2
2020-01-02 3
2020-01-03 3
2020-01-04 3
2020-01-05 5
2020-01-06 7
2020-01-07 9
2020-01-08 9
2020-01-09 9
2020-01-10 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM