在缺少的日期范围内填写数据

时间:2020-09-03 03:42:30

标签: sql sql-server

我有一个表,将具有以下存在数据的数据:

Select Date, [Closing Balance] from StockClosing

Date     | Closing Quantity
---------------------------
20200828 | 5 
20200901 | 10
20200902 | 8    
20200904 | 15
20200905 | 18

表格中有一些缺少的日期,例如20200829到20200831和20200903。 缺少日期的截止数量将按照前一天的截止数量进行跟踪。

我想选择一个包含截止日期的完整日期范围(每天显示)的表格结果。预期结果,

Date     | Closing Quantity
---------------------------
20200828 | 5 
20200829 | 5
20200830 | 5 
20200831 | 5 
20200901 | 10
20200902 | 8    
20200903 | 8    
20200904 | 15
20200905 | 18

除了使用cursor / for循环按1插入丢失的日期和数据外,任何SQL命令都可以一次执行吗?

2 个答案:

答案 0 :(得分:1)

最简单的方法是将LAST_VALUEIGNORE NULLS选项一起使用。可悲的是,SQL Server不支持此功能。有一种使用解析函数的解决方法,但实际上我会提供这个简单的选项,它使用相关的子查询来填充缺失值:

WITH dates AS (
    SELECT '20200828' AS Date UNION ALL
    SELECT '20200829' UNION ALL
    SELECT '20200830' UNION ALL
    SELECT '20200831' UNION ALL
    SELECT '20200901' UNION ALL
    SELECT '20200902' UNION ALL
    SELECT '20200903' UNION ALL
    SELECT '20200904' UNION ALL
    SELECT '20200905'
)

SELECT
    d.Date,
    (SELECT TOP 1 t2.closing FROM StockClosing t2
     WHERE t2.Date <= d.Date AND t2.closing IS NOT NULL
     ORDER BY t2.Date DESC) AS closing
FROM dates d
LEFT JOIN StockClosing t1
    ON d.Date = t1.Date;

screen capture from demo link below

Demo

答案 1 :(得分:1)

您可以选择使用递归CTE。

供参考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