I have a table will the data with exist data below:
Select Date, [Closing Balance] from StockClosing Date | Closing Quantity --------------------------- 20200828 | 5 20200901 | 10 20200902 | 8 20200904 | 15 20200905 | 18
There are some missing date on the table, example 20200829 to 20200831 and 20200903. Those closing quantity of the missing date will be follow as per previous day closing quantity.
I would like select the table result in a full range of date (show everyday) with the closing quantity. Expected result,
Date | Closing Quantity --------------------------- 20200828 | 5 20200829 | 5 20200830 | 5 20200831 | 5 20200901 | 10 20200902 | 8 20200903 | 8 20200904 | 15 20200905 | 18
Beside using cursor/for loop to insert the missing date and data 1 by 1, is that any SQL command can do it at once?
Advertisement
Answer
You have option to use recursive CTE.
For reference Click Here
;with cte as( select max(date) date from YourTable ),cte1 as ( select min(date) date from YourTable union all select dateadd(day,1,cte1.date) date from cte1 where date<(select date from cte) )select c.date,isnull(y.[Closing Quantity], (select top 1 a.[Closing Quantity] from YourTable a where c.date>a.date order by a.date desc) ) as [Closing Quantity] from cte1 c left join YourTable y on c.date=y.date