首页 > 解决方案 > 在 SQL 中填写缺失的时间戳值

问题描述

SQL newby 在这里寻找编写查询的一些帮助。

一些样本数据

时间价值
9:00 1.2
9:01 2.3
9:05 2.4
9:06 2.5

我需要用零填充那些丢失的时间 - 所以查询会返回

时间价值
9:00 1.2
9:01 2.3
9:02 0
9:03 0
9:04 0
9:05 2.4
9:06 2.5

这在 T-SQL 中可能吗?

感谢您的任何帮助/建议...

标签: sqltsqldatetime

解决方案


一种方法使用递归 CTE 生成时间列表,然后用于left join引入值:

with cte as (
      select min(s.time) as time, max(s.time) as maxt
      from sample s
      union all
      select dateadd(minute, 1, cte.time), cte.maxt
      from cte
      where cte.time < cte.maxt
     )
select cte.time, coalesce(s.value, 0)
from cte left join
     sample s
     on cte.time = s.time
order by cte.time;

请注意,如果您有超过 100 分钟,您将需要option (maxrecursion 0)在查询结束时。


推荐阅读